babylon.max.js 3.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228
  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-alpha2";
  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. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14421. this.computeWorldMatrix();
  14422. }
  14423. return this._worldMatrixDeterminant;
  14424. };
  14425. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14426. /**
  14427. * Returns directly the latest state of the mesh World matrix.
  14428. * A Matrix is returned.
  14429. */
  14430. get: function () {
  14431. return this._worldMatrix;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. /**
  14437. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14438. * Returns the AbstractMesh.
  14439. */
  14440. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14441. this._poseMatrix.copyFrom(matrix);
  14442. return this;
  14443. };
  14444. /**
  14445. * Returns the mesh Pose matrix.
  14446. * Returned object : Matrix
  14447. */
  14448. TransformNode.prototype.getPoseMatrix = function () {
  14449. return this._poseMatrix;
  14450. };
  14451. TransformNode.prototype._isSynchronized = function () {
  14452. if (this._isDirty) {
  14453. return false;
  14454. }
  14455. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14456. return false;
  14457. if (this._cache.pivotMatrixUpdated) {
  14458. return false;
  14459. }
  14460. if (this.infiniteDistance) {
  14461. return false;
  14462. }
  14463. if (!this._cache.position.equals(this.position))
  14464. return false;
  14465. if (this.rotationQuaternion) {
  14466. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14467. return false;
  14468. }
  14469. if (!this._cache.rotation.equals(this.rotation))
  14470. return false;
  14471. if (!this._cache.scaling.equals(this.scaling))
  14472. return false;
  14473. return true;
  14474. };
  14475. TransformNode.prototype._initCache = function () {
  14476. _super.prototype._initCache.call(this);
  14477. this._cache.localMatrixUpdated = false;
  14478. this._cache.position = BABYLON.Vector3.Zero();
  14479. this._cache.scaling = BABYLON.Vector3.Zero();
  14480. this._cache.rotation = BABYLON.Vector3.Zero();
  14481. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14482. this._cache.billboardMode = -1;
  14483. };
  14484. TransformNode.prototype.markAsDirty = function (property) {
  14485. if (property === "rotation") {
  14486. this.rotationQuaternion = null;
  14487. }
  14488. this._currentRenderId = Number.MAX_VALUE;
  14489. this._isDirty = true;
  14490. return this;
  14491. };
  14492. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14493. /**
  14494. * Returns the current mesh absolute position.
  14495. * Retuns a Vector3.
  14496. */
  14497. get: function () {
  14498. return this._absolutePosition;
  14499. },
  14500. enumerable: true,
  14501. configurable: true
  14502. });
  14503. /**
  14504. * Sets a new pivot matrix to the mesh.
  14505. * Returns the AbstractMesh.
  14506. */
  14507. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14508. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14509. this._pivotMatrix = matrix.clone();
  14510. this._cache.pivotMatrixUpdated = true;
  14511. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14512. if (this._postMultiplyPivotMatrix) {
  14513. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14514. }
  14515. return this;
  14516. };
  14517. /**
  14518. * Returns the mesh pivot matrix.
  14519. * Default : Identity.
  14520. * A Matrix is returned.
  14521. */
  14522. TransformNode.prototype.getPivotMatrix = function () {
  14523. return this._pivotMatrix;
  14524. };
  14525. /**
  14526. * Prevents the World matrix to be computed any longer.
  14527. * Returns the AbstractMesh.
  14528. */
  14529. TransformNode.prototype.freezeWorldMatrix = function () {
  14530. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14531. this.computeWorldMatrix(true);
  14532. this._isWorldMatrixFrozen = true;
  14533. return this;
  14534. };
  14535. /**
  14536. * Allows back the World matrix computation.
  14537. * Returns the AbstractMesh.
  14538. */
  14539. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14540. this._isWorldMatrixFrozen = false;
  14541. this.computeWorldMatrix(true);
  14542. return this;
  14543. };
  14544. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14545. /**
  14546. * True if the World matrix has been frozen.
  14547. * Returns a boolean.
  14548. */
  14549. get: function () {
  14550. return this._isWorldMatrixFrozen;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. /**
  14556. * Retuns the mesh absolute position in the World.
  14557. * Returns a Vector3.
  14558. */
  14559. TransformNode.prototype.getAbsolutePosition = function () {
  14560. this.computeWorldMatrix();
  14561. return this._absolutePosition;
  14562. };
  14563. /**
  14564. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14565. * Returns the AbstractMesh.
  14566. */
  14567. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14568. if (!absolutePosition) {
  14569. return this;
  14570. }
  14571. var absolutePositionX;
  14572. var absolutePositionY;
  14573. var absolutePositionZ;
  14574. if (absolutePosition.x === undefined) {
  14575. if (arguments.length < 3) {
  14576. return this;
  14577. }
  14578. absolutePositionX = arguments[0];
  14579. absolutePositionY = arguments[1];
  14580. absolutePositionZ = arguments[2];
  14581. }
  14582. else {
  14583. absolutePositionX = absolutePosition.x;
  14584. absolutePositionY = absolutePosition.y;
  14585. absolutePositionZ = absolutePosition.z;
  14586. }
  14587. if (this.parent) {
  14588. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14589. invertParentWorldMatrix.invert();
  14590. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14591. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14592. }
  14593. else {
  14594. this.position.x = absolutePositionX;
  14595. this.position.y = absolutePositionY;
  14596. this.position.z = absolutePositionZ;
  14597. }
  14598. return this;
  14599. };
  14600. /**
  14601. * Sets the mesh position in its local space.
  14602. * Returns the AbstractMesh.
  14603. */
  14604. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14605. this.computeWorldMatrix();
  14606. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14607. return this;
  14608. };
  14609. /**
  14610. * Returns the mesh position in the local space from the current World matrix values.
  14611. * Returns a new Vector3.
  14612. */
  14613. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14614. this.computeWorldMatrix();
  14615. var invLocalWorldMatrix = this._localWorld.clone();
  14616. invLocalWorldMatrix.invert();
  14617. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14618. };
  14619. /**
  14620. * Translates the mesh along the passed Vector3 in its local space.
  14621. * Returns the AbstractMesh.
  14622. */
  14623. TransformNode.prototype.locallyTranslate = function (vector3) {
  14624. this.computeWorldMatrix(true);
  14625. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14626. return this;
  14627. };
  14628. /**
  14629. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14630. * @param targetPoint the position (must be in same space as current mesh) to look at
  14631. * @param yawCor optional yaw (y-axis) correction in radians
  14632. * @param pitchCor optional pitch (x-axis) correction in radians
  14633. * @param rollCor optional roll (z-axis) correction in radians
  14634. * @param space the choosen space of the target
  14635. * @returns the TransformNode.
  14636. */
  14637. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14638. if (yawCor === void 0) { yawCor = 0; }
  14639. if (pitchCor === void 0) { pitchCor = 0; }
  14640. if (rollCor === void 0) { rollCor = 0; }
  14641. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14642. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14643. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14644. targetPoint.subtractToRef(pos, dv);
  14645. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14646. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14647. var pitch = Math.atan2(dv.y, len);
  14648. if (this.rotationQuaternion) {
  14649. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14650. }
  14651. else {
  14652. this.rotation.x = pitch + pitchCor;
  14653. this.rotation.y = yaw + yawCor;
  14654. this.rotation.z = rollCor;
  14655. }
  14656. return this;
  14657. };
  14658. /**
  14659. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14660. * This Vector3 is expressed in the World space.
  14661. */
  14662. TransformNode.prototype.getDirection = function (localAxis) {
  14663. var result = BABYLON.Vector3.Zero();
  14664. this.getDirectionToRef(localAxis, result);
  14665. return result;
  14666. };
  14667. /**
  14668. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14669. * localAxis is expressed in the mesh local space.
  14670. * result is computed in the Wordl space from the mesh World matrix.
  14671. * Returns the AbstractMesh.
  14672. */
  14673. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14674. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14675. return this;
  14676. };
  14677. TransformNode.prototype.setPivotPoint = function (point, space) {
  14678. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14679. if (this.getScene().getRenderId() == 0) {
  14680. this.computeWorldMatrix(true);
  14681. }
  14682. var wm = this.getWorldMatrix();
  14683. if (space == BABYLON.Space.WORLD) {
  14684. var tmat = BABYLON.Tmp.Matrix[0];
  14685. wm.invertToRef(tmat);
  14686. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14687. }
  14688. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14689. this._pivotMatrix.m[12] = -point.x;
  14690. this._pivotMatrix.m[13] = -point.y;
  14691. this._pivotMatrix.m[14] = -point.z;
  14692. this._cache.pivotMatrixUpdated = true;
  14693. return this;
  14694. };
  14695. /**
  14696. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14697. */
  14698. TransformNode.prototype.getPivotPoint = function () {
  14699. var point = BABYLON.Vector3.Zero();
  14700. this.getPivotPointToRef(point);
  14701. return point;
  14702. };
  14703. /**
  14704. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14705. * Returns the AbstractMesh.
  14706. */
  14707. TransformNode.prototype.getPivotPointToRef = function (result) {
  14708. result.x = -this._pivotMatrix.m[12];
  14709. result.y = -this._pivotMatrix.m[13];
  14710. result.z = -this._pivotMatrix.m[14];
  14711. return this;
  14712. };
  14713. /**
  14714. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14715. */
  14716. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14717. var point = BABYLON.Vector3.Zero();
  14718. this.getAbsolutePivotPointToRef(point);
  14719. return point;
  14720. };
  14721. /**
  14722. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14723. * Returns the AbstractMesh.
  14724. */
  14725. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14726. result.x = this._pivotMatrix.m[12];
  14727. result.y = this._pivotMatrix.m[13];
  14728. result.z = this._pivotMatrix.m[14];
  14729. this.getPivotPointToRef(result);
  14730. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14731. return this;
  14732. };
  14733. /**
  14734. * Defines the passed node as the parent of the current node.
  14735. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14736. * Returns the TransformNode.
  14737. */
  14738. TransformNode.prototype.setParent = function (node) {
  14739. if (node === null) {
  14740. var rotation = BABYLON.Tmp.Quaternion[0];
  14741. var position = BABYLON.Tmp.Vector3[0];
  14742. var scale = BABYLON.Tmp.Vector3[1];
  14743. if (this.parent && this.parent.computeWorldMatrix) {
  14744. this.parent.computeWorldMatrix(true);
  14745. }
  14746. this.computeWorldMatrix(true);
  14747. this.getWorldMatrix().decompose(scale, rotation, position);
  14748. if (this.rotationQuaternion) {
  14749. this.rotationQuaternion.copyFrom(rotation);
  14750. }
  14751. else {
  14752. rotation.toEulerAnglesToRef(this.rotation);
  14753. }
  14754. this.scaling.x = scale.x;
  14755. this.scaling.y = scale.y;
  14756. this.scaling.z = scale.z;
  14757. this.position.x = position.x;
  14758. this.position.y = position.y;
  14759. this.position.z = position.z;
  14760. }
  14761. else {
  14762. var rotation = BABYLON.Tmp.Quaternion[0];
  14763. var position = BABYLON.Tmp.Vector3[0];
  14764. var scale = BABYLON.Tmp.Vector3[1];
  14765. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14766. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14767. this.computeWorldMatrix(true);
  14768. node.computeWorldMatrix(true);
  14769. node.getWorldMatrix().invertToRef(invParentMatrix);
  14770. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14771. diffMatrix.decompose(scale, rotation, position);
  14772. if (this.rotationQuaternion) {
  14773. this.rotationQuaternion.copyFrom(rotation);
  14774. }
  14775. else {
  14776. rotation.toEulerAnglesToRef(this.rotation);
  14777. }
  14778. this.position.x = position.x;
  14779. this.position.y = position.y;
  14780. this.position.z = position.z;
  14781. this.scaling.x = scale.x;
  14782. this.scaling.y = scale.y;
  14783. this.scaling.z = scale.z;
  14784. }
  14785. this.parent = node;
  14786. return this;
  14787. };
  14788. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14789. get: function () {
  14790. return this._nonUniformScaling;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14796. if (this._nonUniformScaling === value) {
  14797. return false;
  14798. }
  14799. this._nonUniformScaling = true;
  14800. return true;
  14801. };
  14802. /**
  14803. * Attach the current TransformNode to another TransformNode associated with a bone
  14804. * @param bone Bone affecting the TransformNode
  14805. * @param affectedTransformNode TransformNode associated with the bone
  14806. */
  14807. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14808. this._transformToBoneReferal = affectedTransformNode;
  14809. this.parent = bone;
  14810. if (bone.getWorldMatrix().determinant() < 0) {
  14811. this.scalingDeterminant *= -1;
  14812. }
  14813. return this;
  14814. };
  14815. TransformNode.prototype.detachFromBone = function () {
  14816. if (!this.parent) {
  14817. return this;
  14818. }
  14819. if (this.parent.getWorldMatrix().determinant() < 0) {
  14820. this.scalingDeterminant *= -1;
  14821. }
  14822. this._transformToBoneReferal = null;
  14823. this.parent = null;
  14824. return this;
  14825. };
  14826. /**
  14827. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14828. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14829. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14830. * The passed axis is also normalized.
  14831. * Returns the AbstractMesh.
  14832. */
  14833. TransformNode.prototype.rotate = function (axis, amount, space) {
  14834. axis.normalize();
  14835. if (!this.rotationQuaternion) {
  14836. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14837. this.rotation = BABYLON.Vector3.Zero();
  14838. }
  14839. var rotationQuaternion;
  14840. if (!space || space === BABYLON.Space.LOCAL) {
  14841. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14842. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14843. }
  14844. else {
  14845. if (this.parent) {
  14846. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14847. invertParentWorldMatrix.invert();
  14848. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14849. }
  14850. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14851. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14852. }
  14853. return this;
  14854. };
  14855. /**
  14856. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14857. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14858. * The passed axis is also normalized.
  14859. * Returns the AbstractMesh.
  14860. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14861. */
  14862. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14863. axis.normalize();
  14864. if (!this.rotationQuaternion) {
  14865. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14866. this.rotation.copyFromFloats(0, 0, 0);
  14867. }
  14868. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14869. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14870. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14871. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14872. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14873. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14874. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14875. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14876. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14877. return this;
  14878. };
  14879. /**
  14880. * Translates the mesh along the axis vector for the passed distance in the given space.
  14881. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14882. * Returns the AbstractMesh.
  14883. */
  14884. TransformNode.prototype.translate = function (axis, distance, space) {
  14885. var displacementVector = axis.scale(distance);
  14886. if (!space || space === BABYLON.Space.LOCAL) {
  14887. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14888. this.setPositionWithLocalVector(tempV3);
  14889. }
  14890. else {
  14891. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14892. }
  14893. return this;
  14894. };
  14895. /**
  14896. * Adds a rotation step to the mesh current rotation.
  14897. * x, y, z are Euler angles expressed in radians.
  14898. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14899. * This means this rotation is made in the mesh local space only.
  14900. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14901. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14902. * ```javascript
  14903. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14904. * ```
  14905. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14906. * 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.
  14907. * Returns the AbstractMesh.
  14908. */
  14909. TransformNode.prototype.addRotation = function (x, y, z) {
  14910. var rotationQuaternion;
  14911. if (this.rotationQuaternion) {
  14912. rotationQuaternion = this.rotationQuaternion;
  14913. }
  14914. else {
  14915. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14916. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14917. }
  14918. var accumulation = BABYLON.Tmp.Quaternion[0];
  14919. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14920. rotationQuaternion.multiplyInPlace(accumulation);
  14921. if (!this.rotationQuaternion) {
  14922. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14923. }
  14924. return this;
  14925. };
  14926. /**
  14927. * Computes the mesh World matrix and returns it.
  14928. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14929. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14930. * If the parameter `force`is set to `true`, the actual computation is done.
  14931. * Returns the mesh World Matrix.
  14932. */
  14933. TransformNode.prototype.computeWorldMatrix = function (force) {
  14934. if (this._isWorldMatrixFrozen) {
  14935. return this._worldMatrix;
  14936. }
  14937. if (!force && this.isSynchronized(true)) {
  14938. return this._worldMatrix;
  14939. }
  14940. this._cache.position.copyFrom(this.position);
  14941. this._cache.scaling.copyFrom(this.scaling);
  14942. this._cache.pivotMatrixUpdated = false;
  14943. this._cache.billboardMode = this.billboardMode;
  14944. this._currentRenderId = this.getScene().getRenderId();
  14945. this._isDirty = false;
  14946. // Scaling
  14947. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14948. // Rotation
  14949. //rotate, if quaternion is set and rotation was used
  14950. if (this.rotationQuaternion) {
  14951. var len = this.rotation.length();
  14952. if (len) {
  14953. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14954. this.rotation.copyFromFloats(0, 0, 0);
  14955. }
  14956. }
  14957. if (this.rotationQuaternion) {
  14958. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14959. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14960. }
  14961. else {
  14962. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14963. this._cache.rotation.copyFrom(this.rotation);
  14964. }
  14965. // Translation
  14966. var camera = this.getScene().activeCamera;
  14967. if (this.infiniteDistance && !this.parent && camera) {
  14968. var cameraWorldMatrix = camera.getWorldMatrix();
  14969. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14970. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14971. }
  14972. else {
  14973. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14974. }
  14975. // Composing transformations
  14976. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14977. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14978. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14979. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14980. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14981. // Need to decompose each rotation here
  14982. var currentPosition = BABYLON.Tmp.Vector3[3];
  14983. if (this.parent && this.parent.getWorldMatrix) {
  14984. if (this._transformToBoneReferal) {
  14985. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14986. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14987. }
  14988. else {
  14989. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14990. }
  14991. }
  14992. else {
  14993. currentPosition.copyFrom(this.position);
  14994. }
  14995. currentPosition.subtractInPlace(camera.globalPosition);
  14996. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14997. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  14998. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14999. }
  15000. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15001. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15002. }
  15003. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15004. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15005. }
  15006. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15007. }
  15008. else {
  15009. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15010. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15011. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15012. }
  15013. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15014. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15015. }
  15016. // Local world
  15017. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15018. // Parent
  15019. if (this.parent && this.parent.getWorldMatrix) {
  15020. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15021. if (this._transformToBoneReferal) {
  15022. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15023. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15024. }
  15025. else {
  15026. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15027. }
  15028. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15029. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15030. this._worldMatrix.copyFrom(this._localWorld);
  15031. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15032. }
  15033. else {
  15034. if (this._transformToBoneReferal) {
  15035. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15036. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15037. }
  15038. else {
  15039. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15040. }
  15041. }
  15042. this._markSyncedWithParent();
  15043. }
  15044. else {
  15045. this._worldMatrix.copyFrom(this._localWorld);
  15046. }
  15047. // Post multiply inverse of pivotMatrix
  15048. if (this._postMultiplyPivotMatrix) {
  15049. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15050. }
  15051. // Normal matrix
  15052. if (this.scaling.isNonUniform) {
  15053. this._updateNonUniformScalingState(true);
  15054. }
  15055. else if (this.parent && this.parent._nonUniformScaling) {
  15056. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15057. }
  15058. else {
  15059. this._updateNonUniformScalingState(false);
  15060. }
  15061. this._afterComputeWorldMatrix();
  15062. // Absolute position
  15063. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15064. // Callbacks
  15065. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15066. if (!this._poseMatrix) {
  15067. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15068. }
  15069. // Cache the determinant
  15070. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15071. return this._worldMatrix;
  15072. };
  15073. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15074. };
  15075. /**
  15076. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15077. * @param func: callback function to add
  15078. *
  15079. * Returns the TransformNode.
  15080. */
  15081. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15082. this.onAfterWorldMatrixUpdateObservable.add(func);
  15083. return this;
  15084. };
  15085. /**
  15086. * Removes a registered callback function.
  15087. * Returns the TransformNode.
  15088. */
  15089. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15090. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15091. return this;
  15092. };
  15093. /**
  15094. * Clone the current transform node
  15095. * Returns the new transform node
  15096. * @param name Name of the new clone
  15097. * @param newParent New parent for the clone
  15098. * @param doNotCloneChildren Do not clone children hierarchy
  15099. */
  15100. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15101. var _this = this;
  15102. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15103. result.name = name;
  15104. result.id = name;
  15105. if (newParent) {
  15106. result.parent = newParent;
  15107. }
  15108. if (!doNotCloneChildren) {
  15109. // Children
  15110. var directDescendants = this.getDescendants(true);
  15111. for (var index = 0; index < directDescendants.length; index++) {
  15112. var child = directDescendants[index];
  15113. if (child.clone) {
  15114. child.clone(name + "." + child.name, result);
  15115. }
  15116. }
  15117. }
  15118. return result;
  15119. };
  15120. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15121. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15122. serializationObject.type = this.getClassName();
  15123. // Parent
  15124. if (this.parent) {
  15125. serializationObject.parentId = this.parent.id;
  15126. }
  15127. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15128. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15129. }
  15130. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15131. serializationObject.isEnabled = this.isEnabled();
  15132. // Parent
  15133. if (this.parent) {
  15134. serializationObject.parentId = this.parent.id;
  15135. }
  15136. return serializationObject;
  15137. };
  15138. // Statics
  15139. /**
  15140. * Returns a new TransformNode object parsed from the source provided.
  15141. * The parameter `parsedMesh` is the source.
  15142. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15143. */
  15144. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15145. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15146. if (BABYLON.Tags) {
  15147. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15148. }
  15149. if (parsedTransformNode.localMatrix) {
  15150. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15151. }
  15152. else if (parsedTransformNode.pivotMatrix) {
  15153. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15154. }
  15155. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15156. // Parent
  15157. if (parsedTransformNode.parentId) {
  15158. transformNode._waitingParentId = parsedTransformNode.parentId;
  15159. }
  15160. return transformNode;
  15161. };
  15162. /**
  15163. * Disposes the TransformNode.
  15164. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15165. * Returns nothing.
  15166. */
  15167. TransformNode.prototype.dispose = function (doNotRecurse) {
  15168. // Animations
  15169. this.getScene().stopAnimation(this);
  15170. // Remove from scene
  15171. this.getScene().removeTransformNode(this);
  15172. if (!doNotRecurse) {
  15173. // Children
  15174. var objects = this.getDescendants(true);
  15175. for (var index = 0; index < objects.length; index++) {
  15176. objects[index].dispose();
  15177. }
  15178. }
  15179. else {
  15180. var childMeshes = this.getChildMeshes(true);
  15181. for (index = 0; index < childMeshes.length; index++) {
  15182. var child = childMeshes[index];
  15183. child.parent = null;
  15184. child.computeWorldMatrix(true);
  15185. }
  15186. }
  15187. this.onAfterWorldMatrixUpdateObservable.clear();
  15188. _super.prototype.dispose.call(this);
  15189. };
  15190. // Statics
  15191. TransformNode.BILLBOARDMODE_NONE = 0;
  15192. TransformNode.BILLBOARDMODE_X = 1;
  15193. TransformNode.BILLBOARDMODE_Y = 2;
  15194. TransformNode.BILLBOARDMODE_Z = 4;
  15195. TransformNode.BILLBOARDMODE_ALL = 7;
  15196. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15197. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15198. __decorate([
  15199. BABYLON.serializeAsVector3()
  15200. ], TransformNode.prototype, "_rotation", void 0);
  15201. __decorate([
  15202. BABYLON.serializeAsQuaternion()
  15203. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15204. __decorate([
  15205. BABYLON.serializeAsVector3()
  15206. ], TransformNode.prototype, "_scaling", void 0);
  15207. __decorate([
  15208. BABYLON.serialize()
  15209. ], TransformNode.prototype, "billboardMode", void 0);
  15210. __decorate([
  15211. BABYLON.serialize()
  15212. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15213. __decorate([
  15214. BABYLON.serialize()
  15215. ], TransformNode.prototype, "infiniteDistance", void 0);
  15216. __decorate([
  15217. BABYLON.serializeAsVector3()
  15218. ], TransformNode.prototype, "position", void 0);
  15219. return TransformNode;
  15220. }(BABYLON.Node));
  15221. BABYLON.TransformNode = TransformNode;
  15222. })(BABYLON || (BABYLON = {}));
  15223. //# sourceMappingURL=babylon.transformNode.js.map
  15224. var BABYLON;
  15225. (function (BABYLON) {
  15226. var AbstractMesh = /** @class */ (function (_super) {
  15227. __extends(AbstractMesh, _super);
  15228. // Constructor
  15229. function AbstractMesh(name, scene) {
  15230. if (scene === void 0) { scene = null; }
  15231. var _this = _super.call(this, name, scene, false) || this;
  15232. _this._facetNb = 0; // facet number
  15233. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15234. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15235. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15236. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15237. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15238. _this._subDiv = {
  15239. max: 1,
  15240. X: 1,
  15241. Y: 1,
  15242. Z: 1
  15243. };
  15244. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15245. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15246. // Events
  15247. /**
  15248. * An event triggered when this mesh collides with another one
  15249. * @type {BABYLON.Observable}
  15250. */
  15251. _this.onCollideObservable = new BABYLON.Observable();
  15252. /**
  15253. * An event triggered when the collision's position changes
  15254. * @type {BABYLON.Observable}
  15255. */
  15256. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15257. /**
  15258. * An event triggered when material is changed
  15259. * @type {BABYLON.Observable}
  15260. */
  15261. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15262. // Properties
  15263. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15264. /**
  15265. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15266. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15267. * or
  15268. * 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.
  15269. * for more info check WebGl documentations
  15270. */
  15271. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15272. /**
  15273. * 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:
  15274. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15275. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15276. * 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.
  15277. */
  15278. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15279. /**
  15280. * 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.
  15281. * The default value is -1 which means don't break the query and wait till the result.
  15282. */
  15283. _this.occlusionRetryCount = -1;
  15284. _this._occlusionInternalRetryCounter = 0;
  15285. _this._isOccluded = false;
  15286. _this._isOcclusionQueryInProgress = false;
  15287. _this.visibility = 1.0;
  15288. _this.alphaIndex = Number.MAX_VALUE;
  15289. _this.isVisible = true;
  15290. _this.isPickable = true;
  15291. _this.showBoundingBox = false;
  15292. _this.showSubMeshesBoundingBox = false;
  15293. _this.isBlocker = false;
  15294. _this.enablePointerMoveEvents = false;
  15295. _this.renderingGroupId = 0;
  15296. _this._receiveShadows = false;
  15297. _this.renderOutline = false;
  15298. _this.outlineColor = BABYLON.Color3.Red();
  15299. _this.outlineWidth = 0.02;
  15300. _this.renderOverlay = false;
  15301. _this.overlayColor = BABYLON.Color3.Red();
  15302. _this.overlayAlpha = 0.5;
  15303. _this._hasVertexAlpha = false;
  15304. _this._useVertexColors = true;
  15305. _this._computeBonesUsingShaders = true;
  15306. _this._numBoneInfluencers = 4;
  15307. _this._applyFog = true;
  15308. _this.useOctreeForRenderingSelection = true;
  15309. _this.useOctreeForPicking = true;
  15310. _this.useOctreeForCollisions = true;
  15311. _this._layerMask = 0x0FFFFFFF;
  15312. /**
  15313. * True if the mesh must be rendered in any case.
  15314. */
  15315. _this.alwaysSelectAsActiveMesh = false;
  15316. /**
  15317. * This scene's action manager
  15318. * @type {BABYLON.ActionManager}
  15319. */
  15320. _this.actionManager = null;
  15321. // Physics
  15322. _this.physicsImpostor = null;
  15323. // Collisions
  15324. _this._checkCollisions = false;
  15325. _this._collisionMask = -1;
  15326. _this._collisionGroup = -1;
  15327. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15328. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15329. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15330. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15331. // Edges
  15332. _this.edgesWidth = 1;
  15333. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15334. // Cache
  15335. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15336. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15337. _this._isDisposed = false;
  15338. _this._renderId = 0;
  15339. _this._intersectionsInProgress = new Array();
  15340. _this._unIndexed = false;
  15341. _this._lightSources = new Array();
  15342. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15343. if (collidedMesh === void 0) { collidedMesh = null; }
  15344. //TODO move this to the collision coordinator!
  15345. if (_this.getScene().workerCollisions)
  15346. newPosition.multiplyInPlace(_this._collider._radius);
  15347. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15348. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15349. _this.position.addInPlace(_this._diffPositionForCollisions);
  15350. }
  15351. if (collidedMesh) {
  15352. _this.onCollideObservable.notifyObservers(collidedMesh);
  15353. }
  15354. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15355. };
  15356. _this.getScene().addMesh(_this);
  15357. _this._resyncLightSources();
  15358. return _this;
  15359. }
  15360. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15361. get: function () {
  15362. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15363. },
  15364. enumerable: true,
  15365. configurable: true
  15366. });
  15367. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15368. get: function () {
  15369. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15370. },
  15371. enumerable: true,
  15372. configurable: true
  15373. });
  15374. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15375. get: function () {
  15376. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15377. },
  15378. enumerable: true,
  15379. configurable: true
  15380. });
  15381. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15382. get: function () {
  15383. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15384. },
  15385. enumerable: true,
  15386. configurable: true
  15387. });
  15388. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15389. get: function () {
  15390. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15391. },
  15392. enumerable: true,
  15393. configurable: true
  15394. });
  15395. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15396. /**
  15397. * Read-only : the number of facets in the mesh
  15398. */
  15399. get: function () {
  15400. return this._facetNb;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15406. /**
  15407. * The number (integer) of subdivisions per axis in the partioning space
  15408. */
  15409. get: function () {
  15410. return this._partitioningSubdivisions;
  15411. },
  15412. set: function (nb) {
  15413. this._partitioningSubdivisions = nb;
  15414. },
  15415. enumerable: true,
  15416. configurable: true
  15417. });
  15418. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15419. /**
  15420. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15421. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15422. */
  15423. get: function () {
  15424. return this._partitioningBBoxRatio;
  15425. },
  15426. set: function (ratio) {
  15427. this._partitioningBBoxRatio = ratio;
  15428. },
  15429. enumerable: true,
  15430. configurable: true
  15431. });
  15432. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15433. /**
  15434. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15435. * Works only for updatable meshes.
  15436. * Doesn't work with multi-materials.
  15437. */
  15438. get: function () {
  15439. return this._facetDepthSort;
  15440. },
  15441. set: function (sort) {
  15442. this._facetDepthSort = sort;
  15443. },
  15444. enumerable: true,
  15445. configurable: true
  15446. });
  15447. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15448. /**
  15449. * The location (Vector3) where the facet depth sort must be computed from.
  15450. * By default, the active camera position.
  15451. * Used only when facet depth sort is enabled.
  15452. */
  15453. get: function () {
  15454. return this._facetDepthSortFrom;
  15455. },
  15456. set: function (location) {
  15457. this._facetDepthSortFrom = location;
  15458. },
  15459. enumerable: true,
  15460. configurable: true
  15461. });
  15462. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15463. /**
  15464. * Read-only boolean : is the feature facetData enabled ?
  15465. */
  15466. get: function () {
  15467. return this._facetDataEnabled;
  15468. },
  15469. enumerable: true,
  15470. configurable: true
  15471. });
  15472. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15473. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15474. return false;
  15475. }
  15476. this._markSubMeshesAsMiscDirty();
  15477. return true;
  15478. };
  15479. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15480. set: function (callback) {
  15481. if (this._onCollideObserver) {
  15482. this.onCollideObservable.remove(this._onCollideObserver);
  15483. }
  15484. this._onCollideObserver = this.onCollideObservable.add(callback);
  15485. },
  15486. enumerable: true,
  15487. configurable: true
  15488. });
  15489. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15490. set: function (callback) {
  15491. if (this._onCollisionPositionChangeObserver) {
  15492. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15493. }
  15494. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15495. },
  15496. enumerable: true,
  15497. configurable: true
  15498. });
  15499. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15500. /**
  15501. * 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.
  15502. */
  15503. get: function () {
  15504. return this._isOccluded;
  15505. },
  15506. set: function (value) {
  15507. this._isOccluded = value;
  15508. },
  15509. enumerable: true,
  15510. configurable: true
  15511. });
  15512. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15513. /**
  15514. * Flag to check the progress status of the query
  15515. */
  15516. get: function () {
  15517. return this._isOcclusionQueryInProgress;
  15518. },
  15519. enumerable: true,
  15520. configurable: true
  15521. });
  15522. Object.defineProperty(AbstractMesh.prototype, "material", {
  15523. get: function () {
  15524. return this._material;
  15525. },
  15526. set: function (value) {
  15527. if (this._material === value) {
  15528. return;
  15529. }
  15530. this._material = value;
  15531. if (this.onMaterialChangedObservable.hasObservers) {
  15532. this.onMaterialChangedObservable.notifyObservers(this);
  15533. }
  15534. if (!this.subMeshes) {
  15535. return;
  15536. }
  15537. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15538. var subMesh = _a[_i];
  15539. subMesh.setEffect(null);
  15540. }
  15541. },
  15542. enumerable: true,
  15543. configurable: true
  15544. });
  15545. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15546. get: function () {
  15547. return this._receiveShadows;
  15548. },
  15549. set: function (value) {
  15550. if (this._receiveShadows === value) {
  15551. return;
  15552. }
  15553. this._receiveShadows = value;
  15554. this._markSubMeshesAsLightDirty();
  15555. },
  15556. enumerable: true,
  15557. configurable: true
  15558. });
  15559. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15560. get: function () {
  15561. return this._hasVertexAlpha;
  15562. },
  15563. set: function (value) {
  15564. if (this._hasVertexAlpha === value) {
  15565. return;
  15566. }
  15567. this._hasVertexAlpha = value;
  15568. this._markSubMeshesAsAttributesDirty();
  15569. },
  15570. enumerable: true,
  15571. configurable: true
  15572. });
  15573. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15574. get: function () {
  15575. return this._useVertexColors;
  15576. },
  15577. set: function (value) {
  15578. if (this._useVertexColors === value) {
  15579. return;
  15580. }
  15581. this._useVertexColors = value;
  15582. this._markSubMeshesAsAttributesDirty();
  15583. },
  15584. enumerable: true,
  15585. configurable: true
  15586. });
  15587. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15588. get: function () {
  15589. return this._computeBonesUsingShaders;
  15590. },
  15591. set: function (value) {
  15592. if (this._computeBonesUsingShaders === value) {
  15593. return;
  15594. }
  15595. this._computeBonesUsingShaders = value;
  15596. this._markSubMeshesAsAttributesDirty();
  15597. },
  15598. enumerable: true,
  15599. configurable: true
  15600. });
  15601. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15602. get: function () {
  15603. return this._numBoneInfluencers;
  15604. },
  15605. set: function (value) {
  15606. if (this._numBoneInfluencers === value) {
  15607. return;
  15608. }
  15609. this._numBoneInfluencers = value;
  15610. this._markSubMeshesAsAttributesDirty();
  15611. },
  15612. enumerable: true,
  15613. configurable: true
  15614. });
  15615. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15616. get: function () {
  15617. return this._applyFog;
  15618. },
  15619. set: function (value) {
  15620. if (this._applyFog === value) {
  15621. return;
  15622. }
  15623. this._applyFog = value;
  15624. this._markSubMeshesAsMiscDirty();
  15625. },
  15626. enumerable: true,
  15627. configurable: true
  15628. });
  15629. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15630. get: function () {
  15631. return this._layerMask;
  15632. },
  15633. set: function (value) {
  15634. if (value === this._layerMask) {
  15635. return;
  15636. }
  15637. this._layerMask = value;
  15638. this._resyncLightSources();
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15644. get: function () {
  15645. return this._collisionMask;
  15646. },
  15647. set: function (mask) {
  15648. this._collisionMask = !isNaN(mask) ? mask : -1;
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15654. get: function () {
  15655. return this._collisionGroup;
  15656. },
  15657. set: function (mask) {
  15658. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15659. },
  15660. enumerable: true,
  15661. configurable: true
  15662. });
  15663. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15664. get: function () {
  15665. return null;
  15666. },
  15667. enumerable: true,
  15668. configurable: true
  15669. });
  15670. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15671. get: function () {
  15672. return this._skeleton;
  15673. },
  15674. set: function (value) {
  15675. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15676. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15677. }
  15678. if (value && value.needInitialSkinMatrix) {
  15679. value._registerMeshWithPoseMatrix(this);
  15680. }
  15681. this._skeleton = value;
  15682. if (!this._skeleton) {
  15683. this._bonesTransformMatrices = null;
  15684. }
  15685. this._markSubMeshesAsAttributesDirty();
  15686. },
  15687. enumerable: true,
  15688. configurable: true
  15689. });
  15690. /**
  15691. * Boolean : true if the mesh has been disposed.
  15692. */
  15693. AbstractMesh.prototype.isDisposed = function () {
  15694. return this._isDisposed;
  15695. };
  15696. /**
  15697. * Returns the string "AbstractMesh"
  15698. */
  15699. AbstractMesh.prototype.getClassName = function () {
  15700. return "AbstractMesh";
  15701. };
  15702. /**
  15703. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15704. */
  15705. AbstractMesh.prototype.toString = function (fullDetails) {
  15706. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15707. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15708. if (this._skeleton) {
  15709. ret += ", skeleton: " + this._skeleton.name;
  15710. }
  15711. if (fullDetails) {
  15712. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15713. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15714. }
  15715. return ret;
  15716. };
  15717. AbstractMesh.prototype._rebuild = function () {
  15718. if (this._occlusionQuery) {
  15719. this._occlusionQuery = null;
  15720. }
  15721. if (this._edgesRenderer) {
  15722. this._edgesRenderer._rebuild();
  15723. }
  15724. if (!this.subMeshes) {
  15725. return;
  15726. }
  15727. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15728. var subMesh = _a[_i];
  15729. subMesh._rebuild();
  15730. }
  15731. };
  15732. AbstractMesh.prototype._resyncLightSources = function () {
  15733. this._lightSources.length = 0;
  15734. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15735. var light = _a[_i];
  15736. if (!light.isEnabled()) {
  15737. continue;
  15738. }
  15739. if (light.canAffectMesh(this)) {
  15740. this._lightSources.push(light);
  15741. }
  15742. }
  15743. this._markSubMeshesAsLightDirty();
  15744. };
  15745. AbstractMesh.prototype._resyncLighSource = function (light) {
  15746. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15747. var index = this._lightSources.indexOf(light);
  15748. if (index === -1) {
  15749. if (!isIn) {
  15750. return;
  15751. }
  15752. this._lightSources.push(light);
  15753. }
  15754. else {
  15755. if (isIn) {
  15756. return;
  15757. }
  15758. this._lightSources.splice(index, 1);
  15759. }
  15760. this._markSubMeshesAsLightDirty();
  15761. };
  15762. AbstractMesh.prototype._removeLightSource = function (light) {
  15763. var index = this._lightSources.indexOf(light);
  15764. if (index === -1) {
  15765. return;
  15766. }
  15767. this._lightSources.splice(index, 1);
  15768. };
  15769. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15770. if (!this.subMeshes) {
  15771. return;
  15772. }
  15773. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15774. var subMesh = _a[_i];
  15775. if (subMesh._materialDefines) {
  15776. func(subMesh._materialDefines);
  15777. }
  15778. }
  15779. };
  15780. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15781. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15782. };
  15783. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15784. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15785. };
  15786. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15787. if (!this.subMeshes) {
  15788. return;
  15789. }
  15790. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15791. var subMesh = _a[_i];
  15792. var material = subMesh.getMaterial();
  15793. if (material) {
  15794. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15795. }
  15796. }
  15797. };
  15798. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15799. /**
  15800. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15801. * Default : (1.0, 1.0, 1.0)
  15802. */
  15803. get: function () {
  15804. return this._scaling;
  15805. },
  15806. /**
  15807. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15808. * Default : (1.0, 1.0, 1.0)
  15809. */
  15810. set: function (newScaling) {
  15811. this._scaling = newScaling;
  15812. if (this.physicsImpostor) {
  15813. this.physicsImpostor.forceUpdate();
  15814. }
  15815. },
  15816. enumerable: true,
  15817. configurable: true
  15818. });
  15819. // Methods
  15820. /**
  15821. * Disables the mesh edger rendering mode.
  15822. * Returns the AbstractMesh.
  15823. */
  15824. AbstractMesh.prototype.disableEdgesRendering = function () {
  15825. if (this._edgesRenderer) {
  15826. this._edgesRenderer.dispose();
  15827. this._edgesRenderer = null;
  15828. }
  15829. return this;
  15830. };
  15831. /**
  15832. * Enables the edge rendering mode on the mesh.
  15833. * This mode makes the mesh edges visible.
  15834. * Returns the AbstractMesh.
  15835. */
  15836. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15837. if (epsilon === void 0) { epsilon = 0.95; }
  15838. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15839. this.disableEdgesRendering();
  15840. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15841. return this;
  15842. };
  15843. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15844. /**
  15845. * Returns true if the mesh is blocked. Used by the class Mesh.
  15846. * Returns the boolean `false` by default.
  15847. */
  15848. get: function () {
  15849. return false;
  15850. },
  15851. enumerable: true,
  15852. configurable: true
  15853. });
  15854. /**
  15855. * Returns the mesh itself by default, used by the class Mesh.
  15856. * Returned type : AbstractMesh
  15857. */
  15858. AbstractMesh.prototype.getLOD = function (camera) {
  15859. return this;
  15860. };
  15861. /**
  15862. * Returns 0 by default, used by the class Mesh.
  15863. * Returns an integer.
  15864. */
  15865. AbstractMesh.prototype.getTotalVertices = function () {
  15866. return 0;
  15867. };
  15868. /**
  15869. * Returns null by default, used by the class Mesh.
  15870. * Returned type : integer array
  15871. */
  15872. AbstractMesh.prototype.getIndices = function () {
  15873. return null;
  15874. };
  15875. /**
  15876. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15877. * Returned type : float array or Float32Array
  15878. */
  15879. AbstractMesh.prototype.getVerticesData = function (kind) {
  15880. return null;
  15881. };
  15882. /**
  15883. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15884. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15885. * The `data` are either a numeric array either a Float32Array.
  15886. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15887. * 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).
  15888. * Note that a new underlying VertexBuffer object is created each call.
  15889. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15890. *
  15891. * Possible `kind` values :
  15892. * - BABYLON.VertexBuffer.PositionKind
  15893. * - BABYLON.VertexBuffer.UVKind
  15894. * - BABYLON.VertexBuffer.UV2Kind
  15895. * - BABYLON.VertexBuffer.UV3Kind
  15896. * - BABYLON.VertexBuffer.UV4Kind
  15897. * - BABYLON.VertexBuffer.UV5Kind
  15898. * - BABYLON.VertexBuffer.UV6Kind
  15899. * - BABYLON.VertexBuffer.ColorKind
  15900. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15901. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15902. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15903. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15904. *
  15905. * Returns the Mesh.
  15906. */
  15907. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15908. return this;
  15909. };
  15910. /**
  15911. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15912. * If the mesh has no geometry, it is simply returned as it is.
  15913. * The `data` are either a numeric array either a Float32Array.
  15914. * No new underlying VertexBuffer object is created.
  15915. * 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.
  15916. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15917. *
  15918. * Possible `kind` values :
  15919. * - BABYLON.VertexBuffer.PositionKind
  15920. * - BABYLON.VertexBuffer.UVKind
  15921. * - BABYLON.VertexBuffer.UV2Kind
  15922. * - BABYLON.VertexBuffer.UV3Kind
  15923. * - BABYLON.VertexBuffer.UV4Kind
  15924. * - BABYLON.VertexBuffer.UV5Kind
  15925. * - BABYLON.VertexBuffer.UV6Kind
  15926. * - BABYLON.VertexBuffer.ColorKind
  15927. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15928. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15929. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15930. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15931. *
  15932. * Returns the Mesh.
  15933. */
  15934. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15935. return this;
  15936. };
  15937. /**
  15938. * Sets the mesh indices.
  15939. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15940. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15941. * This method creates a new index buffer each call.
  15942. * Returns the Mesh.
  15943. */
  15944. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15945. return this;
  15946. };
  15947. /** Returns false by default, used by the class Mesh.
  15948. * Returns a boolean
  15949. */
  15950. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15951. return false;
  15952. };
  15953. /**
  15954. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15955. * Returns a BoundingInfo
  15956. */
  15957. AbstractMesh.prototype.getBoundingInfo = function () {
  15958. if (this._masterMesh) {
  15959. return this._masterMesh.getBoundingInfo();
  15960. }
  15961. if (!this._boundingInfo) {
  15962. // this._boundingInfo is being created here
  15963. this._updateBoundingInfo();
  15964. }
  15965. // cannot be null.
  15966. return this._boundingInfo;
  15967. };
  15968. /**
  15969. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15970. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15971. */
  15972. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15973. if (includeDescendants === void 0) { includeDescendants = true; }
  15974. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15975. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15976. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15977. if (maxDimension === 0) {
  15978. return this;
  15979. }
  15980. var scale = 1 / maxDimension;
  15981. this.scaling.scaleInPlace(scale);
  15982. return this;
  15983. };
  15984. /**
  15985. * Sets a mesh new object BoundingInfo.
  15986. * Returns the AbstractMesh.
  15987. */
  15988. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15989. this._boundingInfo = boundingInfo;
  15990. return this;
  15991. };
  15992. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15993. get: function () {
  15994. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15995. },
  15996. enumerable: true,
  15997. configurable: true
  15998. });
  15999. AbstractMesh.prototype._preActivate = function () {
  16000. };
  16001. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16002. };
  16003. AbstractMesh.prototype._activate = function (renderId) {
  16004. this._renderId = renderId;
  16005. };
  16006. /**
  16007. * Returns the latest update of the World matrix
  16008. * Returns a Matrix.
  16009. */
  16010. AbstractMesh.prototype.getWorldMatrix = function () {
  16011. if (this._masterMesh) {
  16012. return this._masterMesh.getWorldMatrix();
  16013. }
  16014. return _super.prototype.getWorldMatrix.call(this);
  16015. };
  16016. /**
  16017. * Returns the latest update of the World matrix determinant.
  16018. */
  16019. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16020. if (this._masterMesh) {
  16021. return this._masterMesh._getWorldMatrixDeterminant();
  16022. }
  16023. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16024. };
  16025. // ================================== Point of View Movement =================================
  16026. /**
  16027. * Perform relative position change from the point of view of behind the front of the mesh.
  16028. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16029. * Supports definition of mesh facing forward or backward.
  16030. * @param {number} amountRight
  16031. * @param {number} amountUp
  16032. * @param {number} amountForward
  16033. *
  16034. * Returns the AbstractMesh.
  16035. */
  16036. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16037. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16038. return this;
  16039. };
  16040. /**
  16041. * Calculate relative position change from the point of view of behind the front of the mesh.
  16042. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16043. * Supports definition of mesh facing forward or backward.
  16044. * @param {number} amountRight
  16045. * @param {number} amountUp
  16046. * @param {number} amountForward
  16047. *
  16048. * Returns a new Vector3.
  16049. */
  16050. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16051. var rotMatrix = new BABYLON.Matrix();
  16052. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16053. rotQuaternion.toRotationMatrix(rotMatrix);
  16054. var translationDelta = BABYLON.Vector3.Zero();
  16055. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16056. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16057. return translationDelta;
  16058. };
  16059. // ================================== Point of View Rotation =================================
  16060. /**
  16061. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16062. * Supports definition of mesh facing forward or backward.
  16063. * @param {number} flipBack
  16064. * @param {number} twirlClockwise
  16065. * @param {number} tiltRight
  16066. *
  16067. * Returns the AbstractMesh.
  16068. */
  16069. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16070. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16071. return this;
  16072. };
  16073. /**
  16074. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16075. * Supports definition of mesh facing forward or backward.
  16076. * @param {number} flipBack
  16077. * @param {number} twirlClockwise
  16078. * @param {number} tiltRight
  16079. *
  16080. * Returns a new Vector3.
  16081. */
  16082. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16083. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16084. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16085. };
  16086. /**
  16087. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16088. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16089. */
  16090. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16091. if (includeDescendants === void 0) { includeDescendants = true; }
  16092. this.computeWorldMatrix(true);
  16093. var min;
  16094. var max;
  16095. var boundingInfo = this.getBoundingInfo();
  16096. if (!this.subMeshes) {
  16097. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16098. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16099. }
  16100. else {
  16101. min = boundingInfo.boundingBox.minimumWorld;
  16102. max = boundingInfo.boundingBox.maximumWorld;
  16103. }
  16104. if (includeDescendants) {
  16105. var descendants = this.getDescendants(false);
  16106. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16107. var descendant = descendants_1[_i];
  16108. var childMesh = descendant;
  16109. childMesh.computeWorldMatrix(true);
  16110. //make sure we have the needed params to get mix and max
  16111. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16112. continue;
  16113. }
  16114. var childBoundingInfo = childMesh.getBoundingInfo();
  16115. var boundingBox = childBoundingInfo.boundingBox;
  16116. var minBox = boundingBox.minimumWorld;
  16117. var maxBox = boundingBox.maximumWorld;
  16118. BABYLON.Tools.CheckExtends(minBox, min, max);
  16119. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16120. }
  16121. }
  16122. return {
  16123. min: min,
  16124. max: max
  16125. };
  16126. };
  16127. /**
  16128. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16129. * Returns the AbstractMesh.
  16130. */
  16131. AbstractMesh.prototype._updateBoundingInfo = function () {
  16132. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16133. this._boundingInfo.update(this.worldMatrixFromCache);
  16134. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16135. return this;
  16136. };
  16137. /**
  16138. * Update a mesh's children BoundingInfo objects only.
  16139. * Returns the AbstractMesh.
  16140. */
  16141. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16142. if (!this.subMeshes) {
  16143. return this;
  16144. }
  16145. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16146. var subMesh = this.subMeshes[subIndex];
  16147. if (!subMesh.IsGlobal) {
  16148. subMesh.updateBoundingInfo(matrix);
  16149. }
  16150. }
  16151. return this;
  16152. };
  16153. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16154. // Bounding info
  16155. this._updateBoundingInfo();
  16156. };
  16157. /**
  16158. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16159. * A mesh is in the frustum if its bounding box intersects the frustum.
  16160. * Boolean returned.
  16161. */
  16162. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16163. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16164. };
  16165. /**
  16166. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16167. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16168. * Boolean returned.
  16169. */
  16170. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16171. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16172. ;
  16173. };
  16174. /**
  16175. * True if the mesh intersects another mesh or a SolidParticle object.
  16176. * 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)
  16177. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16178. * Returns a boolean.
  16179. */
  16180. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16181. if (precise === void 0) { precise = false; }
  16182. if (!this._boundingInfo || !mesh._boundingInfo) {
  16183. return false;
  16184. }
  16185. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16186. return true;
  16187. }
  16188. if (includeDescendants) {
  16189. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16190. var child = _a[_i];
  16191. if (child.intersectsMesh(mesh, precise, true)) {
  16192. return true;
  16193. }
  16194. }
  16195. }
  16196. return false;
  16197. };
  16198. /**
  16199. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16200. * Returns a boolean.
  16201. */
  16202. AbstractMesh.prototype.intersectsPoint = function (point) {
  16203. if (!this._boundingInfo) {
  16204. return false;
  16205. }
  16206. return this._boundingInfo.intersectsPoint(point);
  16207. };
  16208. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16209. return this.physicsImpostor;
  16210. };
  16211. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16212. if (camera === void 0) { camera = null; }
  16213. if (!camera) {
  16214. camera = this.getScene().activeCamera;
  16215. }
  16216. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16217. };
  16218. /**
  16219. * Returns the distance from the mesh to the active camera.
  16220. * Returns a float.
  16221. */
  16222. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16223. if (camera === void 0) { camera = null; }
  16224. if (!camera) {
  16225. camera = this.getScene().activeCamera;
  16226. }
  16227. return this.absolutePosition.subtract(camera.position).length();
  16228. };
  16229. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16230. if (!this.physicsImpostor) {
  16231. return this;
  16232. }
  16233. this.physicsImpostor.applyImpulse(force, contactPoint);
  16234. return this;
  16235. };
  16236. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16237. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16238. return this;
  16239. }
  16240. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16241. mainPivot: pivot1,
  16242. connectedPivot: pivot2,
  16243. nativeParams: options
  16244. });
  16245. return this;
  16246. };
  16247. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16248. // Collisions
  16249. /**
  16250. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16251. * Default `false`.
  16252. */
  16253. get: function () {
  16254. return this._checkCollisions;
  16255. },
  16256. set: function (collisionEnabled) {
  16257. this._checkCollisions = collisionEnabled;
  16258. if (this.getScene().workerCollisions) {
  16259. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16260. }
  16261. },
  16262. enumerable: true,
  16263. configurable: true
  16264. });
  16265. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16266. /**
  16267. * Gets Collider object used to compute collisions (not physics)
  16268. */
  16269. get: function () {
  16270. return this._collider;
  16271. },
  16272. enumerable: true,
  16273. configurable: true
  16274. });
  16275. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16276. var globalPosition = this.getAbsolutePosition();
  16277. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16278. if (!this._collider) {
  16279. this._collider = new BABYLON.Collider();
  16280. }
  16281. this._collider._radius = this.ellipsoid;
  16282. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16283. return this;
  16284. };
  16285. // Submeshes octree
  16286. /**
  16287. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16288. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16289. * Returns an Octree of submeshes.
  16290. */
  16291. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16292. if (maxCapacity === void 0) { maxCapacity = 64; }
  16293. if (maxDepth === void 0) { maxDepth = 2; }
  16294. if (!this._submeshesOctree) {
  16295. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16296. }
  16297. this.computeWorldMatrix(true);
  16298. var boundingInfo = this.getBoundingInfo();
  16299. // Update octree
  16300. var bbox = boundingInfo.boundingBox;
  16301. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16302. return this._submeshesOctree;
  16303. };
  16304. // Collisions
  16305. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16306. this._generatePointsArray();
  16307. if (!this._positions) {
  16308. return this;
  16309. }
  16310. // Transformation
  16311. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16312. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16313. subMesh._lastColliderWorldVertices = [];
  16314. subMesh._trianglePlanes = [];
  16315. var start = subMesh.verticesStart;
  16316. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16317. for (var i = start; i < end; i++) {
  16318. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16319. }
  16320. }
  16321. // Collide
  16322. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16323. if (collider.collisionFound) {
  16324. collider.collidedMesh = this;
  16325. }
  16326. return this;
  16327. };
  16328. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16329. var subMeshes;
  16330. var len;
  16331. // Octrees
  16332. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16333. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16334. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16335. len = intersections.length;
  16336. subMeshes = intersections.data;
  16337. }
  16338. else {
  16339. subMeshes = this.subMeshes;
  16340. len = subMeshes.length;
  16341. }
  16342. for (var index = 0; index < len; index++) {
  16343. var subMesh = subMeshes[index];
  16344. // Bounding test
  16345. if (len > 1 && !subMesh._checkCollision(collider))
  16346. continue;
  16347. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16348. }
  16349. return this;
  16350. };
  16351. AbstractMesh.prototype._checkCollision = function (collider) {
  16352. // Bounding box test
  16353. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16354. return this;
  16355. // Transformation matrix
  16356. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16357. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16358. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16359. return this;
  16360. };
  16361. // Picking
  16362. AbstractMesh.prototype._generatePointsArray = function () {
  16363. return false;
  16364. };
  16365. /**
  16366. * Checks if the passed Ray intersects with the mesh.
  16367. * Returns an object PickingInfo.
  16368. */
  16369. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16370. var pickingInfo = new BABYLON.PickingInfo();
  16371. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16372. return pickingInfo;
  16373. }
  16374. if (!this._generatePointsArray()) {
  16375. return pickingInfo;
  16376. }
  16377. var intersectInfo = null;
  16378. // Octrees
  16379. var subMeshes;
  16380. var len;
  16381. if (this._submeshesOctree && this.useOctreeForPicking) {
  16382. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16383. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16384. len = intersections.length;
  16385. subMeshes = intersections.data;
  16386. }
  16387. else {
  16388. subMeshes = this.subMeshes;
  16389. len = subMeshes.length;
  16390. }
  16391. for (var index = 0; index < len; index++) {
  16392. var subMesh = subMeshes[index];
  16393. // Bounding test
  16394. if (len > 1 && !subMesh.canIntersects(ray))
  16395. continue;
  16396. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16397. if (currentIntersectInfo) {
  16398. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16399. intersectInfo = currentIntersectInfo;
  16400. intersectInfo.subMeshId = index;
  16401. if (fastCheck) {
  16402. break;
  16403. }
  16404. }
  16405. }
  16406. }
  16407. if (intersectInfo) {
  16408. // Get picked point
  16409. var world = this.getWorldMatrix();
  16410. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16411. var direction = ray.direction.clone();
  16412. direction = direction.scale(intersectInfo.distance);
  16413. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16414. var pickedPoint = worldOrigin.add(worldDirection);
  16415. // Return result
  16416. pickingInfo.hit = true;
  16417. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16418. pickingInfo.pickedPoint = pickedPoint;
  16419. pickingInfo.pickedMesh = this;
  16420. pickingInfo.bu = intersectInfo.bu || 0;
  16421. pickingInfo.bv = intersectInfo.bv || 0;
  16422. pickingInfo.faceId = intersectInfo.faceId;
  16423. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16424. return pickingInfo;
  16425. }
  16426. return pickingInfo;
  16427. };
  16428. /**
  16429. * Clones the mesh, used by the class Mesh.
  16430. * Just returns `null` for an AbstractMesh.
  16431. */
  16432. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16433. return null;
  16434. };
  16435. /**
  16436. * Disposes all the mesh submeshes.
  16437. * Returns the AbstractMesh.
  16438. */
  16439. AbstractMesh.prototype.releaseSubMeshes = function () {
  16440. if (this.subMeshes) {
  16441. while (this.subMeshes.length) {
  16442. this.subMeshes[0].dispose();
  16443. }
  16444. }
  16445. else {
  16446. this.subMeshes = new Array();
  16447. }
  16448. return this;
  16449. };
  16450. /**
  16451. * Disposes the AbstractMesh.
  16452. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16453. * Returns nothing.
  16454. */
  16455. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16456. var _this = this;
  16457. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16458. var index;
  16459. // Action manager
  16460. if (this.actionManager !== undefined && this.actionManager !== null) {
  16461. this.actionManager.dispose();
  16462. this.actionManager = null;
  16463. }
  16464. // Skeleton
  16465. this.skeleton = null;
  16466. // Physics
  16467. if (this.physicsImpostor) {
  16468. this.physicsImpostor.dispose();
  16469. }
  16470. // Intersections in progress
  16471. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16472. var other = this._intersectionsInProgress[index];
  16473. var pos = other._intersectionsInProgress.indexOf(this);
  16474. other._intersectionsInProgress.splice(pos, 1);
  16475. }
  16476. this._intersectionsInProgress = [];
  16477. // Lights
  16478. var lights = this.getScene().lights;
  16479. lights.forEach(function (light) {
  16480. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16481. if (meshIndex !== -1) {
  16482. light.includedOnlyMeshes.splice(meshIndex, 1);
  16483. }
  16484. meshIndex = light.excludedMeshes.indexOf(_this);
  16485. if (meshIndex !== -1) {
  16486. light.excludedMeshes.splice(meshIndex, 1);
  16487. }
  16488. // Shadow generators
  16489. var generator = light.getShadowGenerator();
  16490. if (generator) {
  16491. var shadowMap = generator.getShadowMap();
  16492. if (shadowMap && shadowMap.renderList) {
  16493. meshIndex = shadowMap.renderList.indexOf(_this);
  16494. if (meshIndex !== -1) {
  16495. shadowMap.renderList.splice(meshIndex, 1);
  16496. }
  16497. }
  16498. }
  16499. });
  16500. // Edges
  16501. if (this._edgesRenderer) {
  16502. this._edgesRenderer.dispose();
  16503. this._edgesRenderer = null;
  16504. }
  16505. // SubMeshes
  16506. if (this.getClassName() !== "InstancedMesh") {
  16507. this.releaseSubMeshes();
  16508. }
  16509. // Octree
  16510. var sceneOctree = this.getScene().selectionOctree;
  16511. if (sceneOctree !== undefined && sceneOctree !== null) {
  16512. var index = sceneOctree.dynamicContent.indexOf(this);
  16513. if (index !== -1) {
  16514. sceneOctree.dynamicContent.splice(index, 1);
  16515. }
  16516. }
  16517. // Query
  16518. var engine = this.getScene().getEngine();
  16519. if (this._occlusionQuery) {
  16520. this._isOcclusionQueryInProgress = false;
  16521. engine.deleteQuery(this._occlusionQuery);
  16522. this._occlusionQuery = null;
  16523. }
  16524. // Engine
  16525. engine.wipeCaches();
  16526. // Remove from scene
  16527. this.getScene().removeMesh(this);
  16528. if (disposeMaterialAndTextures) {
  16529. if (this.material) {
  16530. this.material.dispose(false, true);
  16531. }
  16532. }
  16533. if (!doNotRecurse) {
  16534. // Particles
  16535. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16536. if (this.getScene().particleSystems[index].emitter === this) {
  16537. this.getScene().particleSystems[index].dispose();
  16538. index--;
  16539. }
  16540. }
  16541. }
  16542. // facet data
  16543. if (this._facetDataEnabled) {
  16544. this.disableFacetData();
  16545. }
  16546. this.onAfterWorldMatrixUpdateObservable.clear();
  16547. this.onCollideObservable.clear();
  16548. this.onCollisionPositionChangeObservable.clear();
  16549. this._isDisposed = true;
  16550. _super.prototype.dispose.call(this, doNotRecurse);
  16551. };
  16552. /**
  16553. * Adds the passed mesh as a child to the current mesh.
  16554. * Returns the AbstractMesh.
  16555. */
  16556. AbstractMesh.prototype.addChild = function (mesh) {
  16557. mesh.setParent(this);
  16558. return this;
  16559. };
  16560. /**
  16561. * Removes the passed mesh from the current mesh children list.
  16562. * Returns the AbstractMesh.
  16563. */
  16564. AbstractMesh.prototype.removeChild = function (mesh) {
  16565. mesh.setParent(null);
  16566. return this;
  16567. };
  16568. // Facet data
  16569. /**
  16570. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16571. * Returns the AbstractMesh.
  16572. */
  16573. AbstractMesh.prototype._initFacetData = function () {
  16574. if (!this._facetNormals) {
  16575. this._facetNormals = new Array();
  16576. }
  16577. if (!this._facetPositions) {
  16578. this._facetPositions = new Array();
  16579. }
  16580. if (!this._facetPartitioning) {
  16581. this._facetPartitioning = new Array();
  16582. }
  16583. this._facetNb = (this.getIndices().length / 3) | 0;
  16584. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16585. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16586. for (var f = 0; f < this._facetNb; f++) {
  16587. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16588. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16589. }
  16590. this._facetDataEnabled = true;
  16591. return this;
  16592. };
  16593. /**
  16594. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16595. * This method can be called within the render loop.
  16596. * 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.
  16597. * Returns the AbstractMesh.
  16598. */
  16599. AbstractMesh.prototype.updateFacetData = function () {
  16600. if (!this._facetDataEnabled) {
  16601. this._initFacetData();
  16602. }
  16603. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16604. var indices = this.getIndices();
  16605. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16606. var bInfo = this.getBoundingInfo();
  16607. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16608. // init arrays, matrix and sort function on first call
  16609. this._facetDepthSortEnabled = true;
  16610. if (indices instanceof Uint16Array) {
  16611. this._depthSortedIndices = new Uint16Array(indices);
  16612. }
  16613. else if (indices instanceof Uint32Array) {
  16614. this._depthSortedIndices = new Uint32Array(indices);
  16615. }
  16616. else {
  16617. var needs32bits = false;
  16618. for (var i = 0; i < indices.length; i++) {
  16619. if (indices[i] > 65535) {
  16620. needs32bits = true;
  16621. break;
  16622. }
  16623. }
  16624. if (needs32bits) {
  16625. this._depthSortedIndices = new Uint32Array(indices);
  16626. }
  16627. else {
  16628. this._depthSortedIndices = new Uint16Array(indices);
  16629. }
  16630. }
  16631. this._facetDepthSortFunction = function (f1, f2) {
  16632. return (f2.sqDistance - f1.sqDistance);
  16633. };
  16634. if (!this._facetDepthSortFrom) {
  16635. var camera = this.getScene().activeCamera;
  16636. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16637. }
  16638. this._depthSortedFacets = [];
  16639. for (var f = 0; f < this._facetNb; f++) {
  16640. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16641. this._depthSortedFacets.push(depthSortedFacet);
  16642. }
  16643. this._invertedMatrix = BABYLON.Matrix.Identity();
  16644. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16645. }
  16646. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16647. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16648. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16649. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16650. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16651. this._subDiv.max = this._partitioningSubdivisions;
  16652. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16653. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16654. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16655. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16656. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16657. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16658. // set the parameters for ComputeNormals()
  16659. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16660. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16661. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16662. this._facetParameters.bInfo = bInfo;
  16663. this._facetParameters.bbSize = this._bbSize;
  16664. this._facetParameters.subDiv = this._subDiv;
  16665. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16666. this._facetParameters.depthSort = this._facetDepthSort;
  16667. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16668. this.computeWorldMatrix(true);
  16669. this._worldMatrix.invertToRef(this._invertedMatrix);
  16670. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16671. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16672. }
  16673. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16674. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16675. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16676. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16677. var l = (this._depthSortedIndices.length / 3) | 0;
  16678. for (var f = 0; f < l; f++) {
  16679. var sind = this._depthSortedFacets[f].ind;
  16680. this._depthSortedIndices[f * 3] = indices[sind];
  16681. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16682. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16683. }
  16684. this.updateIndices(this._depthSortedIndices);
  16685. }
  16686. return this;
  16687. };
  16688. /**
  16689. * Returns the facetLocalNormals array.
  16690. * The normals are expressed in the mesh local space.
  16691. */
  16692. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16693. if (!this._facetNormals) {
  16694. this.updateFacetData();
  16695. }
  16696. return this._facetNormals;
  16697. };
  16698. /**
  16699. * Returns the facetLocalPositions array.
  16700. * The facet positions are expressed in the mesh local space.
  16701. */
  16702. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16703. if (!this._facetPositions) {
  16704. this.updateFacetData();
  16705. }
  16706. return this._facetPositions;
  16707. };
  16708. /**
  16709. * Returns the facetLocalPartioning array.
  16710. */
  16711. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16712. if (!this._facetPartitioning) {
  16713. this.updateFacetData();
  16714. }
  16715. return this._facetPartitioning;
  16716. };
  16717. /**
  16718. * Returns the i-th facet position in the world system.
  16719. * This method allocates a new Vector3 per call.
  16720. */
  16721. AbstractMesh.prototype.getFacetPosition = function (i) {
  16722. var pos = BABYLON.Vector3.Zero();
  16723. this.getFacetPositionToRef(i, pos);
  16724. return pos;
  16725. };
  16726. /**
  16727. * Sets the reference Vector3 with the i-th facet position in the world system.
  16728. * Returns the AbstractMesh.
  16729. */
  16730. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16731. var localPos = (this.getFacetLocalPositions())[i];
  16732. var world = this.getWorldMatrix();
  16733. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16734. return this;
  16735. };
  16736. /**
  16737. * Returns the i-th facet normal in the world system.
  16738. * This method allocates a new Vector3 per call.
  16739. */
  16740. AbstractMesh.prototype.getFacetNormal = function (i) {
  16741. var norm = BABYLON.Vector3.Zero();
  16742. this.getFacetNormalToRef(i, norm);
  16743. return norm;
  16744. };
  16745. /**
  16746. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16747. * Returns the AbstractMesh.
  16748. */
  16749. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16750. var localNorm = (this.getFacetLocalNormals())[i];
  16751. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16752. return this;
  16753. };
  16754. /**
  16755. * 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).
  16756. */
  16757. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16758. var bInfo = this.getBoundingInfo();
  16759. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16760. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16761. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16762. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16763. return null;
  16764. }
  16765. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16766. };
  16767. /**
  16768. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16769. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16770. * 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.
  16771. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16772. * 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.
  16773. */
  16774. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16775. if (checkFace === void 0) { checkFace = false; }
  16776. if (facing === void 0) { facing = true; }
  16777. var world = this.getWorldMatrix();
  16778. var invMat = BABYLON.Tmp.Matrix[5];
  16779. world.invertToRef(invMat);
  16780. var invVect = BABYLON.Tmp.Vector3[8];
  16781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16782. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16783. if (projected) {
  16784. // tranform the local computed projected vector to world coordinates
  16785. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16786. }
  16787. return closest;
  16788. };
  16789. /**
  16790. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16791. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16792. * 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.
  16793. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16794. * 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.
  16795. */
  16796. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16797. if (checkFace === void 0) { checkFace = false; }
  16798. if (facing === void 0) { facing = true; }
  16799. var closest = null;
  16800. var tmpx = 0.0;
  16801. var tmpy = 0.0;
  16802. var tmpz = 0.0;
  16803. var d = 0.0; // tmp dot facet normal * facet position
  16804. var t0 = 0.0;
  16805. var projx = 0.0;
  16806. var projy = 0.0;
  16807. var projz = 0.0;
  16808. // Get all the facets in the same partitioning block than (x, y, z)
  16809. var facetPositions = this.getFacetLocalPositions();
  16810. var facetNormals = this.getFacetLocalNormals();
  16811. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16812. if (!facetsInBlock) {
  16813. return null;
  16814. }
  16815. // Get the closest facet to (x, y, z)
  16816. var shortest = Number.MAX_VALUE; // init distance vars
  16817. var tmpDistance = shortest;
  16818. var fib; // current facet in the block
  16819. var norm; // current facet normal
  16820. var p0; // current facet barycenter position
  16821. // loop on all the facets in the current partitioning block
  16822. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16823. fib = facetsInBlock[idx];
  16824. norm = facetNormals[fib];
  16825. p0 = facetPositions[fib];
  16826. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16827. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16828. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16829. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16830. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16831. projx = x + norm.x * t0;
  16832. projy = y + norm.y * t0;
  16833. projz = z + norm.z * t0;
  16834. tmpx = projx - x;
  16835. tmpy = projy - y;
  16836. tmpz = projz - z;
  16837. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16838. if (tmpDistance < shortest) {
  16839. shortest = tmpDistance;
  16840. closest = fib;
  16841. if (projected) {
  16842. projected.x = projx;
  16843. projected.y = projy;
  16844. projected.z = projz;
  16845. }
  16846. }
  16847. }
  16848. }
  16849. return closest;
  16850. };
  16851. /**
  16852. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16853. */
  16854. AbstractMesh.prototype.getFacetDataParameters = function () {
  16855. return this._facetParameters;
  16856. };
  16857. /**
  16858. * Disables the feature FacetData and frees the related memory.
  16859. * Returns the AbstractMesh.
  16860. */
  16861. AbstractMesh.prototype.disableFacetData = function () {
  16862. if (this._facetDataEnabled) {
  16863. this._facetDataEnabled = false;
  16864. this._facetPositions = new Array();
  16865. this._facetNormals = new Array();
  16866. this._facetPartitioning = new Array();
  16867. this._facetParameters = null;
  16868. this._depthSortedIndices = new Uint32Array(0);
  16869. }
  16870. return this;
  16871. };
  16872. /**
  16873. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16874. * Returns the mesh.
  16875. */
  16876. AbstractMesh.prototype.updateIndices = function (indices) {
  16877. return this;
  16878. };
  16879. /**
  16880. * The mesh Geometry. Actually used by the Mesh object.
  16881. * Returns a blank geometry object.
  16882. */
  16883. /**
  16884. * Creates new normals data for the mesh.
  16885. * @param updatable.
  16886. */
  16887. AbstractMesh.prototype.createNormals = function (updatable) {
  16888. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16889. var indices = this.getIndices();
  16890. var normals;
  16891. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16892. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16893. }
  16894. else {
  16895. normals = [];
  16896. }
  16897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16898. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16899. };
  16900. /**
  16901. * Align the mesh with a normal.
  16902. * Returns the mesh.
  16903. */
  16904. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16905. if (!upDirection) {
  16906. upDirection = BABYLON.Axis.Y;
  16907. }
  16908. var axisX = BABYLON.Tmp.Vector3[0];
  16909. var axisZ = BABYLON.Tmp.Vector3[1];
  16910. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16911. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16912. if (this.rotationQuaternion) {
  16913. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16914. }
  16915. else {
  16916. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16917. }
  16918. return this;
  16919. };
  16920. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16921. var engine = this.getEngine();
  16922. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16923. this._isOccluded = false;
  16924. return;
  16925. }
  16926. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16927. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16928. if (isOcclusionQueryAvailable) {
  16929. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16930. this._isOcclusionQueryInProgress = false;
  16931. this._occlusionInternalRetryCounter = 0;
  16932. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16933. }
  16934. else {
  16935. this._occlusionInternalRetryCounter++;
  16936. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16937. this._isOcclusionQueryInProgress = false;
  16938. this._occlusionInternalRetryCounter = 0;
  16939. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16940. // if strict continue the last state of the object.
  16941. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16942. }
  16943. else {
  16944. return;
  16945. }
  16946. }
  16947. }
  16948. var scene = this.getScene();
  16949. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16950. if (!this._occlusionQuery) {
  16951. this._occlusionQuery = engine.createQuery();
  16952. }
  16953. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16954. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16955. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16956. this._isOcclusionQueryInProgress = true;
  16957. };
  16958. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16959. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16960. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16961. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16962. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16963. return AbstractMesh;
  16964. }(BABYLON.TransformNode));
  16965. BABYLON.AbstractMesh = AbstractMesh;
  16966. })(BABYLON || (BABYLON = {}));
  16967. //# sourceMappingURL=babylon.abstractMesh.js.map
  16968. var BABYLON;
  16969. (function (BABYLON) {
  16970. var Light = /** @class */ (function (_super) {
  16971. __extends(Light, _super);
  16972. /**
  16973. * Creates a Light object in the scene.
  16974. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16975. */
  16976. function Light(name, scene) {
  16977. var _this = _super.call(this, name, scene) || this;
  16978. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16979. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16980. _this.intensity = 1.0;
  16981. _this.range = Number.MAX_VALUE;
  16982. /**
  16983. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16984. * of light.
  16985. */
  16986. _this._photometricScale = 1.0;
  16987. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16988. _this._radius = 0.00001;
  16989. _this.renderPriority = 0;
  16990. /**
  16991. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16992. * the current shadow generator.
  16993. */
  16994. _this.shadowEnabled = true;
  16995. _this._excludeWithLayerMask = 0;
  16996. _this._includeOnlyWithLayerMask = 0;
  16997. _this._lightmapMode = 0;
  16998. _this._excludedMeshesIds = new Array();
  16999. _this._includedOnlyMeshesIds = new Array();
  17000. _this.getScene().addLight(_this);
  17001. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17002. _this._buildUniformLayout();
  17003. _this.includedOnlyMeshes = new Array();
  17004. _this.excludedMeshes = new Array();
  17005. _this._resyncMeshes();
  17006. return _this;
  17007. }
  17008. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17009. /**
  17010. * If every light affecting the material is in this lightmapMode,
  17011. * material.lightmapTexture adds or multiplies
  17012. * (depends on material.useLightmapAsShadowmap)
  17013. * after every other light calculations.
  17014. */
  17015. get: function () {
  17016. return Light._LIGHTMAP_DEFAULT;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17022. /**
  17023. * material.lightmapTexture as only diffuse lighting from this light
  17024. * adds pnly specular lighting from this light
  17025. * adds dynamic shadows
  17026. */
  17027. get: function () {
  17028. return Light._LIGHTMAP_SPECULAR;
  17029. },
  17030. enumerable: true,
  17031. configurable: true
  17032. });
  17033. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17034. /**
  17035. * material.lightmapTexture as only lighting
  17036. * no light calculation from this light
  17037. * only adds dynamic shadows from this light
  17038. */
  17039. get: function () {
  17040. return Light._LIGHTMAP_SHADOWSONLY;
  17041. },
  17042. enumerable: true,
  17043. configurable: true
  17044. });
  17045. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17046. /**
  17047. * Each light type uses the default quantity according to its type:
  17048. * point/spot lights use luminous intensity
  17049. * directional lights use illuminance
  17050. */
  17051. get: function () {
  17052. return Light._INTENSITYMODE_AUTOMATIC;
  17053. },
  17054. enumerable: true,
  17055. configurable: true
  17056. });
  17057. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17058. /**
  17059. * lumen (lm)
  17060. */
  17061. get: function () {
  17062. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17068. /**
  17069. * candela (lm/sr)
  17070. */
  17071. get: function () {
  17072. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17073. },
  17074. enumerable: true,
  17075. configurable: true
  17076. });
  17077. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17078. /**
  17079. * lux (lm/m^2)
  17080. */
  17081. get: function () {
  17082. return Light._INTENSITYMODE_ILLUMINANCE;
  17083. },
  17084. enumerable: true,
  17085. configurable: true
  17086. });
  17087. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17088. /**
  17089. * nit (cd/m^2)
  17090. */
  17091. get: function () {
  17092. return Light._INTENSITYMODE_LUMINANCE;
  17093. },
  17094. enumerable: true,
  17095. configurable: true
  17096. });
  17097. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17098. /**
  17099. * Light type const id of the point light.
  17100. */
  17101. get: function () {
  17102. return Light._LIGHTTYPEID_POINTLIGHT;
  17103. },
  17104. enumerable: true,
  17105. configurable: true
  17106. });
  17107. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17108. /**
  17109. * Light type const id of the directional light.
  17110. */
  17111. get: function () {
  17112. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17118. /**
  17119. * Light type const id of the spot light.
  17120. */
  17121. get: function () {
  17122. return Light._LIGHTTYPEID_SPOTLIGHT;
  17123. },
  17124. enumerable: true,
  17125. configurable: true
  17126. });
  17127. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17128. /**
  17129. * Light type const id of the hemispheric light.
  17130. */
  17131. get: function () {
  17132. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Object.defineProperty(Light.prototype, "intensityMode", {
  17138. /**
  17139. * Gets the photometric scale used to interpret the intensity.
  17140. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17141. */
  17142. get: function () {
  17143. return this._intensityMode;
  17144. },
  17145. /**
  17146. * Sets the photometric scale used to interpret the intensity.
  17147. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17148. */
  17149. set: function (value) {
  17150. this._intensityMode = value;
  17151. this._computePhotometricScale();
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. ;
  17157. ;
  17158. Object.defineProperty(Light.prototype, "radius", {
  17159. /**
  17160. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17161. */
  17162. get: function () {
  17163. return this._radius;
  17164. },
  17165. /**
  17166. * sets the light radius used by PBR Materials to simulate soft area lights.
  17167. */
  17168. set: function (value) {
  17169. this._radius = value;
  17170. this._computePhotometricScale();
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. ;
  17176. ;
  17177. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17178. get: function () {
  17179. return this._includedOnlyMeshes;
  17180. },
  17181. set: function (value) {
  17182. this._includedOnlyMeshes = value;
  17183. this._hookArrayForIncludedOnly(value);
  17184. },
  17185. enumerable: true,
  17186. configurable: true
  17187. });
  17188. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17189. get: function () {
  17190. return this._excludedMeshes;
  17191. },
  17192. set: function (value) {
  17193. this._excludedMeshes = value;
  17194. this._hookArrayForExcluded(value);
  17195. },
  17196. enumerable: true,
  17197. configurable: true
  17198. });
  17199. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17200. get: function () {
  17201. return this._excludeWithLayerMask;
  17202. },
  17203. set: function (value) {
  17204. this._excludeWithLayerMask = value;
  17205. this._resyncMeshes();
  17206. },
  17207. enumerable: true,
  17208. configurable: true
  17209. });
  17210. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17211. get: function () {
  17212. return this._includeOnlyWithLayerMask;
  17213. },
  17214. set: function (value) {
  17215. this._includeOnlyWithLayerMask = value;
  17216. this._resyncMeshes();
  17217. },
  17218. enumerable: true,
  17219. configurable: true
  17220. });
  17221. Object.defineProperty(Light.prototype, "lightmapMode", {
  17222. get: function () {
  17223. return this._lightmapMode;
  17224. },
  17225. set: function (value) {
  17226. if (this._lightmapMode === value) {
  17227. return;
  17228. }
  17229. this._lightmapMode = value;
  17230. this._markMeshesAsLightDirty();
  17231. },
  17232. enumerable: true,
  17233. configurable: true
  17234. });
  17235. Light.prototype._buildUniformLayout = function () {
  17236. // Overridden
  17237. };
  17238. /**
  17239. * Returns the string "Light".
  17240. */
  17241. Light.prototype.getClassName = function () {
  17242. return "Light";
  17243. };
  17244. /**
  17245. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17246. */
  17247. Light.prototype.toString = function (fullDetails) {
  17248. var ret = "Name: " + this.name;
  17249. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17250. if (this.animations) {
  17251. for (var i = 0; i < this.animations.length; i++) {
  17252. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17253. }
  17254. }
  17255. if (fullDetails) {
  17256. }
  17257. return ret;
  17258. };
  17259. /**
  17260. * Set the enabled state of this node.
  17261. * @param {boolean} value - the new enabled state
  17262. * @see isEnabled
  17263. */
  17264. Light.prototype.setEnabled = function (value) {
  17265. _super.prototype.setEnabled.call(this, value);
  17266. this._resyncMeshes();
  17267. };
  17268. /**
  17269. * Returns the Light associated shadow generator.
  17270. */
  17271. Light.prototype.getShadowGenerator = function () {
  17272. return this._shadowGenerator;
  17273. };
  17274. /**
  17275. * Returns a Vector3, the absolute light position in the World.
  17276. */
  17277. Light.prototype.getAbsolutePosition = function () {
  17278. return BABYLON.Vector3.Zero();
  17279. };
  17280. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17281. };
  17282. Light.prototype._getWorldMatrix = function () {
  17283. return BABYLON.Matrix.Identity();
  17284. };
  17285. /**
  17286. * Boolean : True if the light will affect the passed mesh.
  17287. */
  17288. Light.prototype.canAffectMesh = function (mesh) {
  17289. if (!mesh) {
  17290. return true;
  17291. }
  17292. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17293. return false;
  17294. }
  17295. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17296. return false;
  17297. }
  17298. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17299. return false;
  17300. }
  17301. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17302. return false;
  17303. }
  17304. return true;
  17305. };
  17306. /**
  17307. * Returns the light World matrix.
  17308. */
  17309. Light.prototype.getWorldMatrix = function () {
  17310. this._currentRenderId = this.getScene().getRenderId();
  17311. var worldMatrix = this._getWorldMatrix();
  17312. if (this.parent && this.parent.getWorldMatrix) {
  17313. if (!this._parentedWorldMatrix) {
  17314. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17315. }
  17316. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17317. this._markSyncedWithParent();
  17318. return this._parentedWorldMatrix;
  17319. }
  17320. return worldMatrix;
  17321. };
  17322. /**
  17323. * Sort function to order lights for rendering.
  17324. * @param a First Light object to compare to second.
  17325. * @param b Second Light object to compare first.
  17326. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17327. */
  17328. Light.compareLightsPriority = function (a, b) {
  17329. //shadow-casting lights have priority over non-shadow-casting lights
  17330. //the renderPrioirty is a secondary sort criterion
  17331. if (a.shadowEnabled !== b.shadowEnabled) {
  17332. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17333. }
  17334. return b.renderPriority - a.renderPriority;
  17335. };
  17336. /**
  17337. * Disposes the light.
  17338. */
  17339. Light.prototype.dispose = function () {
  17340. if (this._shadowGenerator) {
  17341. this._shadowGenerator.dispose();
  17342. this._shadowGenerator = null;
  17343. }
  17344. // Animations
  17345. this.getScene().stopAnimation(this);
  17346. this._uniformBuffer.dispose();
  17347. // Remove from scene
  17348. this.getScene().removeLight(this);
  17349. _super.prototype.dispose.call(this);
  17350. };
  17351. /**
  17352. * Returns the light type ID (integer).
  17353. */
  17354. Light.prototype.getTypeID = function () {
  17355. return 0;
  17356. };
  17357. /**
  17358. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17359. */
  17360. Light.prototype.getScaledIntensity = function () {
  17361. return this._photometricScale * this.intensity;
  17362. };
  17363. /**
  17364. * Returns a new Light object, named "name", from the current one.
  17365. */
  17366. Light.prototype.clone = function (name) {
  17367. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17368. if (!constructor) {
  17369. return null;
  17370. }
  17371. return BABYLON.SerializationHelper.Clone(constructor, this);
  17372. };
  17373. /**
  17374. * Serializes the current light into a Serialization object.
  17375. * Returns the serialized object.
  17376. */
  17377. Light.prototype.serialize = function () {
  17378. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17379. // Type
  17380. serializationObject.type = this.getTypeID();
  17381. // Parent
  17382. if (this.parent) {
  17383. serializationObject.parentId = this.parent.id;
  17384. }
  17385. // Inclusion / exclusions
  17386. if (this.excludedMeshes.length > 0) {
  17387. serializationObject.excludedMeshesIds = [];
  17388. this.excludedMeshes.forEach(function (mesh) {
  17389. serializationObject.excludedMeshesIds.push(mesh.id);
  17390. });
  17391. }
  17392. if (this.includedOnlyMeshes.length > 0) {
  17393. serializationObject.includedOnlyMeshesIds = [];
  17394. this.includedOnlyMeshes.forEach(function (mesh) {
  17395. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17396. });
  17397. }
  17398. // Animations
  17399. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17400. serializationObject.ranges = this.serializeAnimationRanges();
  17401. return serializationObject;
  17402. };
  17403. /**
  17404. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17405. * This new light is named "name" and added to the passed scene.
  17406. */
  17407. Light.GetConstructorFromName = function (type, name, scene) {
  17408. switch (type) {
  17409. case 0:
  17410. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17411. case 1:
  17412. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17413. case 2:
  17414. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17415. case 3:
  17416. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17417. }
  17418. return null;
  17419. };
  17420. /**
  17421. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17422. */
  17423. Light.Parse = function (parsedLight, scene) {
  17424. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17425. if (!constructor) {
  17426. return null;
  17427. }
  17428. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17429. // Inclusion / exclusions
  17430. if (parsedLight.excludedMeshesIds) {
  17431. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17432. }
  17433. if (parsedLight.includedOnlyMeshesIds) {
  17434. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17435. }
  17436. // Parent
  17437. if (parsedLight.parentId) {
  17438. light._waitingParentId = parsedLight.parentId;
  17439. }
  17440. // Animations
  17441. if (parsedLight.animations) {
  17442. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17443. var parsedAnimation = parsedLight.animations[animationIndex];
  17444. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17445. }
  17446. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17447. }
  17448. if (parsedLight.autoAnimate) {
  17449. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17450. }
  17451. return light;
  17452. };
  17453. Light.prototype._hookArrayForExcluded = function (array) {
  17454. var _this = this;
  17455. var oldPush = array.push;
  17456. array.push = function () {
  17457. var items = [];
  17458. for (var _i = 0; _i < arguments.length; _i++) {
  17459. items[_i] = arguments[_i];
  17460. }
  17461. var result = oldPush.apply(array, items);
  17462. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17463. var item = items_1[_a];
  17464. item._resyncLighSource(_this);
  17465. }
  17466. return result;
  17467. };
  17468. var oldSplice = array.splice;
  17469. array.splice = function (index, deleteCount) {
  17470. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17471. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17472. var item = deleted_1[_i];
  17473. item._resyncLighSource(_this);
  17474. }
  17475. return deleted;
  17476. };
  17477. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17478. var item = array_1[_i];
  17479. item._resyncLighSource(this);
  17480. }
  17481. };
  17482. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17483. var _this = this;
  17484. var oldPush = array.push;
  17485. array.push = function () {
  17486. var items = [];
  17487. for (var _i = 0; _i < arguments.length; _i++) {
  17488. items[_i] = arguments[_i];
  17489. }
  17490. var result = oldPush.apply(array, items);
  17491. _this._resyncMeshes();
  17492. return result;
  17493. };
  17494. var oldSplice = array.splice;
  17495. array.splice = function (index, deleteCount) {
  17496. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17497. _this._resyncMeshes();
  17498. return deleted;
  17499. };
  17500. this._resyncMeshes();
  17501. };
  17502. Light.prototype._resyncMeshes = function () {
  17503. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17504. var mesh = _a[_i];
  17505. mesh._resyncLighSource(this);
  17506. }
  17507. };
  17508. Light.prototype._markMeshesAsLightDirty = function () {
  17509. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17510. var mesh = _a[_i];
  17511. if (mesh._lightSources.indexOf(this) !== -1) {
  17512. mesh._markSubMeshesAsLightDirty();
  17513. }
  17514. }
  17515. };
  17516. /**
  17517. * Recomputes the cached photometric scale if needed.
  17518. */
  17519. Light.prototype._computePhotometricScale = function () {
  17520. this._photometricScale = this._getPhotometricScale();
  17521. this.getScene().resetCachedMaterial();
  17522. };
  17523. /**
  17524. * Returns the Photometric Scale according to the light type and intensity mode.
  17525. */
  17526. Light.prototype._getPhotometricScale = function () {
  17527. var photometricScale = 0.0;
  17528. var lightTypeID = this.getTypeID();
  17529. //get photometric mode
  17530. var photometricMode = this.intensityMode;
  17531. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17532. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17533. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17534. }
  17535. else {
  17536. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17537. }
  17538. }
  17539. //compute photometric scale
  17540. switch (lightTypeID) {
  17541. case Light.LIGHTTYPEID_POINTLIGHT:
  17542. case Light.LIGHTTYPEID_SPOTLIGHT:
  17543. switch (photometricMode) {
  17544. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17545. photometricScale = 1.0 / (4.0 * Math.PI);
  17546. break;
  17547. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17548. photometricScale = 1.0;
  17549. break;
  17550. case Light.INTENSITYMODE_LUMINANCE:
  17551. photometricScale = this.radius * this.radius;
  17552. break;
  17553. }
  17554. break;
  17555. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17556. switch (photometricMode) {
  17557. case Light.INTENSITYMODE_ILLUMINANCE:
  17558. photometricScale = 1.0;
  17559. break;
  17560. case Light.INTENSITYMODE_LUMINANCE:
  17561. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17562. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17563. var apexAngleRadians = this.radius;
  17564. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17565. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17566. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17567. photometricScale = solidAngle;
  17568. break;
  17569. }
  17570. break;
  17571. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17572. // No fall off in hemisperic light.
  17573. photometricScale = 1.0;
  17574. break;
  17575. }
  17576. return photometricScale;
  17577. };
  17578. Light.prototype._reorderLightsInScene = function () {
  17579. var scene = this.getScene();
  17580. if (this._renderPriority != 0) {
  17581. scene.requireLightSorting = true;
  17582. }
  17583. this.getScene().sortLightsByPriority();
  17584. };
  17585. //lightmapMode Consts
  17586. Light._LIGHTMAP_DEFAULT = 0;
  17587. Light._LIGHTMAP_SPECULAR = 1;
  17588. Light._LIGHTMAP_SHADOWSONLY = 2;
  17589. // Intensity Mode Consts
  17590. Light._INTENSITYMODE_AUTOMATIC = 0;
  17591. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17592. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17593. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17594. Light._INTENSITYMODE_LUMINANCE = 4;
  17595. // Light types ids const.
  17596. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17597. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17598. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17599. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17600. __decorate([
  17601. BABYLON.serializeAsColor3()
  17602. ], Light.prototype, "diffuse", void 0);
  17603. __decorate([
  17604. BABYLON.serializeAsColor3()
  17605. ], Light.prototype, "specular", void 0);
  17606. __decorate([
  17607. BABYLON.serialize()
  17608. ], Light.prototype, "intensity", void 0);
  17609. __decorate([
  17610. BABYLON.serialize()
  17611. ], Light.prototype, "range", void 0);
  17612. __decorate([
  17613. BABYLON.serialize()
  17614. ], Light.prototype, "intensityMode", null);
  17615. __decorate([
  17616. BABYLON.serialize()
  17617. ], Light.prototype, "radius", null);
  17618. __decorate([
  17619. BABYLON.serialize()
  17620. ], Light.prototype, "_renderPriority", void 0);
  17621. __decorate([
  17622. BABYLON.expandToProperty("_reorderLightsInScene")
  17623. ], Light.prototype, "renderPriority", void 0);
  17624. __decorate([
  17625. BABYLON.serialize()
  17626. ], Light.prototype, "shadowEnabled", void 0);
  17627. __decorate([
  17628. BABYLON.serialize("excludeWithLayerMask")
  17629. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17630. __decorate([
  17631. BABYLON.serialize("includeOnlyWithLayerMask")
  17632. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17633. __decorate([
  17634. BABYLON.serialize("lightmapMode")
  17635. ], Light.prototype, "_lightmapMode", void 0);
  17636. return Light;
  17637. }(BABYLON.Node));
  17638. BABYLON.Light = Light;
  17639. })(BABYLON || (BABYLON = {}));
  17640. //# sourceMappingURL=babylon.light.js.map
  17641. var BABYLON;
  17642. (function (BABYLON) {
  17643. var Camera = /** @class */ (function (_super) {
  17644. __extends(Camera, _super);
  17645. function Camera(name, position, scene) {
  17646. var _this = _super.call(this, name, scene) || this;
  17647. _this.upVector = BABYLON.Vector3.Up();
  17648. _this.orthoLeft = null;
  17649. _this.orthoRight = null;
  17650. _this.orthoBottom = null;
  17651. _this.orthoTop = null;
  17652. /**
  17653. * default : 0.8
  17654. * FOV is set in Radians.
  17655. */
  17656. _this.fov = 0.8;
  17657. _this.minZ = 1;
  17658. _this.maxZ = 10000.0;
  17659. _this.inertia = 0.9;
  17660. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17661. _this.isIntermediate = false;
  17662. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17663. /**
  17664. * Restricts the camera to viewing objects with the same layerMask.
  17665. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17666. */
  17667. _this.layerMask = 0x0FFFFFFF;
  17668. /**
  17669. * default : FOVMODE_VERTICAL_FIXED
  17670. * fovMode sets the camera frustum bounds to the viewport bounds.
  17671. */
  17672. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17673. // Camera rig members
  17674. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17675. _this._rigCameras = new Array();
  17676. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17677. _this._skipRendering = false;
  17678. _this.customRenderTargets = new Array();
  17679. // Observables
  17680. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17681. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17682. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17683. _this.onRestoreStateObservable = new BABYLON.Observable();
  17684. // Cache
  17685. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17686. _this._projectionMatrix = new BABYLON.Matrix();
  17687. _this._doNotComputeProjectionMatrix = false;
  17688. _this._postProcesses = new Array();
  17689. _this._transformMatrix = BABYLON.Matrix.Zero();
  17690. _this._activeMeshes = new BABYLON.SmartArray(256);
  17691. _this._globalPosition = BABYLON.Vector3.Zero();
  17692. _this._refreshFrustumPlanes = true;
  17693. _this.getScene().addCamera(_this);
  17694. if (!_this.getScene().activeCamera) {
  17695. _this.getScene().activeCamera = _this;
  17696. }
  17697. _this.position = position;
  17698. return _this;
  17699. }
  17700. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17701. get: function () {
  17702. return Camera._PERSPECTIVE_CAMERA;
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17708. get: function () {
  17709. return Camera._ORTHOGRAPHIC_CAMERA;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17715. /**
  17716. * This is the default FOV mode for perspective cameras.
  17717. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17718. *
  17719. */
  17720. get: function () {
  17721. return Camera._FOVMODE_VERTICAL_FIXED;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17727. /**
  17728. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17729. *
  17730. */
  17731. get: function () {
  17732. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17738. get: function () {
  17739. return Camera._RIG_MODE_NONE;
  17740. },
  17741. enumerable: true,
  17742. configurable: true
  17743. });
  17744. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17745. get: function () {
  17746. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17752. get: function () {
  17753. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17754. },
  17755. enumerable: true,
  17756. configurable: true
  17757. });
  17758. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17759. get: function () {
  17760. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17766. get: function () {
  17767. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17773. get: function () {
  17774. return Camera._RIG_MODE_VR;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17780. get: function () {
  17781. return Camera._RIG_MODE_WEBVR;
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. /**
  17787. * Store current camera state (fov, position, etc..)
  17788. */
  17789. Camera.prototype.storeState = function () {
  17790. this._stateStored = true;
  17791. this._storedFov = this.fov;
  17792. return this;
  17793. };
  17794. /**
  17795. * Restores the camera state values if it has been stored. You must call storeState() first
  17796. */
  17797. Camera.prototype._restoreStateValues = function () {
  17798. if (!this._stateStored) {
  17799. return false;
  17800. }
  17801. this.fov = this._storedFov;
  17802. return true;
  17803. };
  17804. /**
  17805. * Restored camera state. You must call storeState() first
  17806. */
  17807. Camera.prototype.restoreState = function () {
  17808. if (this._restoreStateValues()) {
  17809. this.onRestoreStateObservable.notifyObservers(this);
  17810. return true;
  17811. }
  17812. return false;
  17813. };
  17814. Camera.prototype.getClassName = function () {
  17815. return "Camera";
  17816. };
  17817. /**
  17818. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17819. */
  17820. Camera.prototype.toString = function (fullDetails) {
  17821. var ret = "Name: " + this.name;
  17822. ret += ", type: " + this.getClassName();
  17823. if (this.animations) {
  17824. for (var i = 0; i < this.animations.length; i++) {
  17825. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17826. }
  17827. }
  17828. if (fullDetails) {
  17829. }
  17830. return ret;
  17831. };
  17832. Object.defineProperty(Camera.prototype, "globalPosition", {
  17833. get: function () {
  17834. return this._globalPosition;
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Camera.prototype.getActiveMeshes = function () {
  17840. return this._activeMeshes;
  17841. };
  17842. Camera.prototype.isActiveMesh = function (mesh) {
  17843. return (this._activeMeshes.indexOf(mesh) !== -1);
  17844. };
  17845. //Cache
  17846. Camera.prototype._initCache = function () {
  17847. _super.prototype._initCache.call(this);
  17848. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17849. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17850. this._cache.mode = undefined;
  17851. this._cache.minZ = undefined;
  17852. this._cache.maxZ = undefined;
  17853. this._cache.fov = undefined;
  17854. this._cache.fovMode = undefined;
  17855. this._cache.aspectRatio = undefined;
  17856. this._cache.orthoLeft = undefined;
  17857. this._cache.orthoRight = undefined;
  17858. this._cache.orthoBottom = undefined;
  17859. this._cache.orthoTop = undefined;
  17860. this._cache.renderWidth = undefined;
  17861. this._cache.renderHeight = undefined;
  17862. };
  17863. Camera.prototype._updateCache = function (ignoreParentClass) {
  17864. if (!ignoreParentClass) {
  17865. _super.prototype._updateCache.call(this);
  17866. }
  17867. this._cache.position.copyFrom(this.position);
  17868. this._cache.upVector.copyFrom(this.upVector);
  17869. };
  17870. // Synchronized
  17871. Camera.prototype._isSynchronized = function () {
  17872. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17873. };
  17874. Camera.prototype._isSynchronizedViewMatrix = function () {
  17875. if (!_super.prototype._isSynchronized.call(this))
  17876. return false;
  17877. return this._cache.position.equals(this.position)
  17878. && this._cache.upVector.equals(this.upVector)
  17879. && this.isSynchronizedWithParent();
  17880. };
  17881. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17882. var check = this._cache.mode === this.mode
  17883. && this._cache.minZ === this.minZ
  17884. && this._cache.maxZ === this.maxZ;
  17885. if (!check) {
  17886. return false;
  17887. }
  17888. var engine = this.getEngine();
  17889. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17890. check = this._cache.fov === this.fov
  17891. && this._cache.fovMode === this.fovMode
  17892. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17893. }
  17894. else {
  17895. check = this._cache.orthoLeft === this.orthoLeft
  17896. && this._cache.orthoRight === this.orthoRight
  17897. && this._cache.orthoBottom === this.orthoBottom
  17898. && this._cache.orthoTop === this.orthoTop
  17899. && this._cache.renderWidth === engine.getRenderWidth()
  17900. && this._cache.renderHeight === engine.getRenderHeight();
  17901. }
  17902. return check;
  17903. };
  17904. // Controls
  17905. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17906. };
  17907. Camera.prototype.detachControl = function (element) {
  17908. };
  17909. Camera.prototype.update = function () {
  17910. this._checkInputs();
  17911. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17912. this._updateRigCameras();
  17913. }
  17914. };
  17915. Camera.prototype._checkInputs = function () {
  17916. this.onAfterCheckInputsObservable.notifyObservers(this);
  17917. };
  17918. Object.defineProperty(Camera.prototype, "rigCameras", {
  17919. get: function () {
  17920. return this._rigCameras;
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17926. get: function () {
  17927. return this._rigPostProcess;
  17928. },
  17929. enumerable: true,
  17930. configurable: true
  17931. });
  17932. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17933. // invalidate framebuffer
  17934. if (this._postProcesses.length > 0) {
  17935. this._postProcesses[0].markTextureDirty();
  17936. }
  17937. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17938. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17939. var cam = this._rigCameras[i];
  17940. var rigPostProcess = cam._rigPostProcess;
  17941. // for VR rig, there does not have to be a post process
  17942. if (rigPostProcess) {
  17943. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17944. if (isPass) {
  17945. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17946. cam.isIntermediate = this._postProcesses.length === 0;
  17947. }
  17948. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17949. rigPostProcess.markTextureDirty();
  17950. }
  17951. else {
  17952. cam._postProcesses = this._postProcesses.slice(0);
  17953. }
  17954. }
  17955. };
  17956. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17957. if (insertAt === void 0) { insertAt = null; }
  17958. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17959. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17960. return 0;
  17961. }
  17962. if (insertAt == null || insertAt < 0) {
  17963. this._postProcesses.push(postProcess);
  17964. }
  17965. else {
  17966. this._postProcesses.splice(insertAt, 0, postProcess);
  17967. }
  17968. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17969. return this._postProcesses.indexOf(postProcess);
  17970. };
  17971. Camera.prototype.detachPostProcess = function (postProcess) {
  17972. var idx = this._postProcesses.indexOf(postProcess);
  17973. if (idx !== -1) {
  17974. this._postProcesses.splice(idx, 1);
  17975. }
  17976. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17977. };
  17978. Camera.prototype.getWorldMatrix = function () {
  17979. if (!this._worldMatrix) {
  17980. this._worldMatrix = BABYLON.Matrix.Identity();
  17981. }
  17982. var viewMatrix = this.getViewMatrix();
  17983. viewMatrix.invertToRef(this._worldMatrix);
  17984. return this._worldMatrix;
  17985. };
  17986. Camera.prototype._getViewMatrix = function () {
  17987. return BABYLON.Matrix.Identity();
  17988. };
  17989. Camera.prototype.getViewMatrix = function (force) {
  17990. if (!force && this._isSynchronizedViewMatrix()) {
  17991. return this._computedViewMatrix;
  17992. }
  17993. this.updateCache();
  17994. this._computedViewMatrix = this._getViewMatrix();
  17995. this._currentRenderId = this.getScene().getRenderId();
  17996. this._refreshFrustumPlanes = true;
  17997. if (!this.parent || !this.parent.getWorldMatrix) {
  17998. this._globalPosition.copyFrom(this.position);
  17999. }
  18000. else {
  18001. if (!this._worldMatrix) {
  18002. this._worldMatrix = BABYLON.Matrix.Identity();
  18003. }
  18004. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18005. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18006. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18007. this._computedViewMatrix.invert();
  18008. this._markSyncedWithParent();
  18009. }
  18010. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18011. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18012. }
  18013. this.onViewMatrixChangedObservable.notifyObservers(this);
  18014. return this._computedViewMatrix;
  18015. };
  18016. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18017. this._doNotComputeProjectionMatrix = true;
  18018. if (projection !== undefined) {
  18019. this._projectionMatrix = projection;
  18020. }
  18021. };
  18022. ;
  18023. Camera.prototype.unfreezeProjectionMatrix = function () {
  18024. this._doNotComputeProjectionMatrix = false;
  18025. };
  18026. ;
  18027. Camera.prototype.getProjectionMatrix = function (force) {
  18028. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18029. return this._projectionMatrix;
  18030. }
  18031. // Cache
  18032. this._cache.mode = this.mode;
  18033. this._cache.minZ = this.minZ;
  18034. this._cache.maxZ = this.maxZ;
  18035. // Matrix
  18036. this._refreshFrustumPlanes = true;
  18037. var engine = this.getEngine();
  18038. var scene = this.getScene();
  18039. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18040. this._cache.fov = this.fov;
  18041. this._cache.fovMode = this.fovMode;
  18042. this._cache.aspectRatio = engine.getAspectRatio(this);
  18043. if (this.minZ <= 0) {
  18044. this.minZ = 0.1;
  18045. }
  18046. if (scene.useRightHandedSystem) {
  18047. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18048. }
  18049. else {
  18050. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18051. }
  18052. }
  18053. else {
  18054. var halfWidth = engine.getRenderWidth() / 2.0;
  18055. var halfHeight = engine.getRenderHeight() / 2.0;
  18056. if (scene.useRightHandedSystem) {
  18057. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18058. }
  18059. else {
  18060. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18061. }
  18062. this._cache.orthoLeft = this.orthoLeft;
  18063. this._cache.orthoRight = this.orthoRight;
  18064. this._cache.orthoBottom = this.orthoBottom;
  18065. this._cache.orthoTop = this.orthoTop;
  18066. this._cache.renderWidth = engine.getRenderWidth();
  18067. this._cache.renderHeight = engine.getRenderHeight();
  18068. }
  18069. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18070. return this._projectionMatrix;
  18071. };
  18072. Camera.prototype.getTranformationMatrix = function () {
  18073. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18074. return this._transformMatrix;
  18075. };
  18076. Camera.prototype.updateFrustumPlanes = function () {
  18077. if (!this._refreshFrustumPlanes) {
  18078. return;
  18079. }
  18080. this.getTranformationMatrix();
  18081. if (!this._frustumPlanes) {
  18082. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18083. }
  18084. else {
  18085. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18086. }
  18087. this._refreshFrustumPlanes = false;
  18088. };
  18089. Camera.prototype.isInFrustum = function (target) {
  18090. this.updateFrustumPlanes();
  18091. return target.isInFrustum(this._frustumPlanes);
  18092. };
  18093. Camera.prototype.isCompletelyInFrustum = function (target) {
  18094. this.updateFrustumPlanes();
  18095. return target.isCompletelyInFrustum(this._frustumPlanes);
  18096. };
  18097. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18098. if (length === void 0) { length = 100; }
  18099. if (!transform) {
  18100. transform = this.getWorldMatrix();
  18101. }
  18102. if (!origin) {
  18103. origin = this.position;
  18104. }
  18105. var forward = new BABYLON.Vector3(0, 0, 1);
  18106. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18107. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18108. return new BABYLON.Ray(origin, direction, length);
  18109. };
  18110. Camera.prototype.dispose = function () {
  18111. // Observables
  18112. this.onViewMatrixChangedObservable.clear();
  18113. this.onProjectionMatrixChangedObservable.clear();
  18114. this.onAfterCheckInputsObservable.clear();
  18115. this.onRestoreStateObservable.clear();
  18116. // Inputs
  18117. if (this.inputs) {
  18118. this.inputs.clear();
  18119. }
  18120. // Animations
  18121. this.getScene().stopAnimation(this);
  18122. // Remove from scene
  18123. this.getScene().removeCamera(this);
  18124. while (this._rigCameras.length > 0) {
  18125. var camera = this._rigCameras.pop();
  18126. if (camera) {
  18127. camera.dispose();
  18128. }
  18129. }
  18130. // Postprocesses
  18131. if (this._rigPostProcess) {
  18132. this._rigPostProcess.dispose(this);
  18133. this._rigPostProcess = null;
  18134. this._postProcesses = [];
  18135. }
  18136. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18137. this._rigPostProcess = null;
  18138. this._postProcesses = [];
  18139. }
  18140. else {
  18141. var i = this._postProcesses.length;
  18142. while (--i >= 0) {
  18143. this._postProcesses[i].dispose(this);
  18144. }
  18145. }
  18146. // Render targets
  18147. var i = this.customRenderTargets.length;
  18148. while (--i >= 0) {
  18149. this.customRenderTargets[i].dispose();
  18150. }
  18151. this.customRenderTargets = [];
  18152. // Active Meshes
  18153. this._activeMeshes.dispose();
  18154. _super.prototype.dispose.call(this);
  18155. };
  18156. Object.defineProperty(Camera.prototype, "leftCamera", {
  18157. // ---- Camera rigs section ----
  18158. get: function () {
  18159. if (this._rigCameras.length < 1) {
  18160. return null;
  18161. }
  18162. return this._rigCameras[0];
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(Camera.prototype, "rightCamera", {
  18168. get: function () {
  18169. if (this._rigCameras.length < 2) {
  18170. return null;
  18171. }
  18172. return this._rigCameras[1];
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Camera.prototype.getLeftTarget = function () {
  18178. if (this._rigCameras.length < 1) {
  18179. return null;
  18180. }
  18181. return this._rigCameras[0].getTarget();
  18182. };
  18183. Camera.prototype.getRightTarget = function () {
  18184. if (this._rigCameras.length < 2) {
  18185. return null;
  18186. }
  18187. return this._rigCameras[1].getTarget();
  18188. };
  18189. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18190. if (this.cameraRigMode === mode) {
  18191. return;
  18192. }
  18193. while (this._rigCameras.length > 0) {
  18194. var camera = this._rigCameras.pop();
  18195. if (camera) {
  18196. camera.dispose();
  18197. }
  18198. }
  18199. this.cameraRigMode = mode;
  18200. this._cameraRigParams = {};
  18201. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18202. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18203. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18204. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18205. // create the rig cameras, unless none
  18206. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18207. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18208. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18209. if (leftCamera && rightCamera) {
  18210. this._rigCameras.push(leftCamera);
  18211. this._rigCameras.push(rightCamera);
  18212. }
  18213. }
  18214. switch (this.cameraRigMode) {
  18215. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18216. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18217. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18218. break;
  18219. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18220. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18221. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18222. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18223. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18224. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18225. break;
  18226. case Camera.RIG_MODE_VR:
  18227. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18228. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18229. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18230. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18231. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18232. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18233. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18234. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18235. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18236. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18237. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18238. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18239. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18240. if (metrics.compensateDistortion) {
  18241. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18242. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18243. }
  18244. break;
  18245. case Camera.RIG_MODE_WEBVR:
  18246. if (rigParams.vrDisplay) {
  18247. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18248. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18249. //Left eye
  18250. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18251. this._rigCameras[0].setCameraRigParameter("left", true);
  18252. //leaving this for future reference
  18253. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18254. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18255. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18256. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18257. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18258. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18259. this._rigCameras[0].parent = this;
  18260. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18261. //Right eye
  18262. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18263. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18264. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18265. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18266. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18267. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18268. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18269. this._rigCameras[1].parent = this;
  18270. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18271. if (Camera.UseAlternateWebVRRendering) {
  18272. this._rigCameras[1]._skipRendering = true;
  18273. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18274. }
  18275. }
  18276. break;
  18277. }
  18278. this._cascadePostProcessesToRigCams();
  18279. this.update();
  18280. };
  18281. Camera.prototype._getVRProjectionMatrix = function () {
  18282. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18283. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18284. return this._projectionMatrix;
  18285. };
  18286. Camera.prototype._updateCameraRotationMatrix = function () {
  18287. //Here for WebVR
  18288. };
  18289. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18290. //Here for WebVR
  18291. };
  18292. /**
  18293. * This function MUST be overwritten by the different WebVR cameras available.
  18294. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18295. */
  18296. Camera.prototype._getWebVRProjectionMatrix = function () {
  18297. return BABYLON.Matrix.Identity();
  18298. };
  18299. /**
  18300. * This function MUST be overwritten by the different WebVR cameras available.
  18301. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18302. */
  18303. Camera.prototype._getWebVRViewMatrix = function () {
  18304. return BABYLON.Matrix.Identity();
  18305. };
  18306. Camera.prototype.setCameraRigParameter = function (name, value) {
  18307. if (!this._cameraRigParams) {
  18308. this._cameraRigParams = {};
  18309. }
  18310. this._cameraRigParams[name] = value;
  18311. //provisionnally:
  18312. if (name === "interaxialDistance") {
  18313. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18314. }
  18315. };
  18316. /**
  18317. * needs to be overridden by children so sub has required properties to be copied
  18318. */
  18319. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18320. return null;
  18321. };
  18322. /**
  18323. * May need to be overridden by children
  18324. */
  18325. Camera.prototype._updateRigCameras = function () {
  18326. for (var i = 0; i < this._rigCameras.length; i++) {
  18327. this._rigCameras[i].minZ = this.minZ;
  18328. this._rigCameras[i].maxZ = this.maxZ;
  18329. this._rigCameras[i].fov = this.fov;
  18330. }
  18331. // only update viewport when ANAGLYPH
  18332. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18333. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18334. }
  18335. };
  18336. Camera.prototype._setupInputs = function () {
  18337. };
  18338. Camera.prototype.serialize = function () {
  18339. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18340. // Type
  18341. serializationObject.type = this.getClassName();
  18342. // Parent
  18343. if (this.parent) {
  18344. serializationObject.parentId = this.parent.id;
  18345. }
  18346. if (this.inputs) {
  18347. this.inputs.serialize(serializationObject);
  18348. }
  18349. // Animations
  18350. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18351. serializationObject.ranges = this.serializeAnimationRanges();
  18352. return serializationObject;
  18353. };
  18354. Camera.prototype.clone = function (name) {
  18355. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18356. };
  18357. Camera.prototype.getDirection = function (localAxis) {
  18358. var result = BABYLON.Vector3.Zero();
  18359. this.getDirectionToRef(localAxis, result);
  18360. return result;
  18361. };
  18362. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18363. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18364. };
  18365. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18366. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18367. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18368. switch (type) {
  18369. case "ArcRotateCamera":
  18370. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18371. case "DeviceOrientationCamera":
  18372. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18373. case "FollowCamera":
  18374. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18375. case "ArcFollowCamera":
  18376. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18377. case "GamepadCamera":
  18378. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18379. case "TouchCamera":
  18380. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18381. case "VirtualJoysticksCamera":
  18382. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18383. case "WebVRFreeCamera":
  18384. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18385. case "WebVRGamepadCamera":
  18386. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18387. case "VRDeviceOrientationFreeCamera":
  18388. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18389. case "VRDeviceOrientationGamepadCamera":
  18390. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18391. case "AnaglyphArcRotateCamera":
  18392. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18393. case "AnaglyphFreeCamera":
  18394. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18395. case "AnaglyphGamepadCamera":
  18396. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18397. case "AnaglyphUniversalCamera":
  18398. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18399. case "StereoscopicArcRotateCamera":
  18400. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18401. case "StereoscopicFreeCamera":
  18402. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18403. case "StereoscopicGamepadCamera":
  18404. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18405. case "StereoscopicUniversalCamera":
  18406. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18407. case "FreeCamera":// Forcing Universal here
  18408. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18409. default:// Universal Camera is the default value
  18410. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18411. }
  18412. };
  18413. Camera.prototype.computeWorldMatrix = function () {
  18414. return this.getWorldMatrix();
  18415. };
  18416. Camera.Parse = function (parsedCamera, scene) {
  18417. var type = parsedCamera.type;
  18418. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18419. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18420. // Parent
  18421. if (parsedCamera.parentId) {
  18422. camera._waitingParentId = parsedCamera.parentId;
  18423. }
  18424. //If camera has an input manager, let it parse inputs settings
  18425. if (camera.inputs) {
  18426. camera.inputs.parse(parsedCamera);
  18427. camera._setupInputs();
  18428. }
  18429. if (camera.setPosition) {
  18430. camera.position.copyFromFloats(0, 0, 0);
  18431. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18432. }
  18433. // Target
  18434. if (parsedCamera.target) {
  18435. if (camera.setTarget) {
  18436. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18437. }
  18438. }
  18439. // Apply 3d rig, when found
  18440. if (parsedCamera.cameraRigMode) {
  18441. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18442. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18443. }
  18444. // Animations
  18445. if (parsedCamera.animations) {
  18446. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18447. var parsedAnimation = parsedCamera.animations[animationIndex];
  18448. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18449. }
  18450. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18451. }
  18452. if (parsedCamera.autoAnimate) {
  18453. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18454. }
  18455. return camera;
  18456. };
  18457. // Statics
  18458. Camera._PERSPECTIVE_CAMERA = 0;
  18459. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18460. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18461. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18462. Camera._RIG_MODE_NONE = 0;
  18463. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18464. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18465. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18466. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18467. Camera._RIG_MODE_VR = 20;
  18468. Camera._RIG_MODE_WEBVR = 21;
  18469. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18470. Camera.UseAlternateWebVRRendering = false;
  18471. __decorate([
  18472. BABYLON.serializeAsVector3()
  18473. ], Camera.prototype, "position", void 0);
  18474. __decorate([
  18475. BABYLON.serializeAsVector3()
  18476. ], Camera.prototype, "upVector", void 0);
  18477. __decorate([
  18478. BABYLON.serialize()
  18479. ], Camera.prototype, "orthoLeft", void 0);
  18480. __decorate([
  18481. BABYLON.serialize()
  18482. ], Camera.prototype, "orthoRight", void 0);
  18483. __decorate([
  18484. BABYLON.serialize()
  18485. ], Camera.prototype, "orthoBottom", void 0);
  18486. __decorate([
  18487. BABYLON.serialize()
  18488. ], Camera.prototype, "orthoTop", void 0);
  18489. __decorate([
  18490. BABYLON.serialize()
  18491. ], Camera.prototype, "fov", void 0);
  18492. __decorate([
  18493. BABYLON.serialize()
  18494. ], Camera.prototype, "minZ", void 0);
  18495. __decorate([
  18496. BABYLON.serialize()
  18497. ], Camera.prototype, "maxZ", void 0);
  18498. __decorate([
  18499. BABYLON.serialize()
  18500. ], Camera.prototype, "inertia", void 0);
  18501. __decorate([
  18502. BABYLON.serialize()
  18503. ], Camera.prototype, "mode", void 0);
  18504. __decorate([
  18505. BABYLON.serialize()
  18506. ], Camera.prototype, "layerMask", void 0);
  18507. __decorate([
  18508. BABYLON.serialize()
  18509. ], Camera.prototype, "fovMode", void 0);
  18510. __decorate([
  18511. BABYLON.serialize()
  18512. ], Camera.prototype, "cameraRigMode", void 0);
  18513. __decorate([
  18514. BABYLON.serialize()
  18515. ], Camera.prototype, "interaxialDistance", void 0);
  18516. __decorate([
  18517. BABYLON.serialize()
  18518. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18519. return Camera;
  18520. }(BABYLON.Node));
  18521. BABYLON.Camera = Camera;
  18522. })(BABYLON || (BABYLON = {}));
  18523. //# sourceMappingURL=babylon.camera.js.map
  18524. var BABYLON;
  18525. (function (BABYLON) {
  18526. var RenderingManager = /** @class */ (function () {
  18527. function RenderingManager(scene) {
  18528. this._renderingGroups = new Array();
  18529. this._autoClearDepthStencil = {};
  18530. this._customOpaqueSortCompareFn = {};
  18531. this._customAlphaTestSortCompareFn = {};
  18532. this._customTransparentSortCompareFn = {};
  18533. this._renderinGroupInfo = null;
  18534. this._scene = scene;
  18535. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18536. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18537. }
  18538. }
  18539. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18540. if (depth === void 0) { depth = true; }
  18541. if (stencil === void 0) { stencil = true; }
  18542. if (this._depthStencilBufferAlreadyCleaned) {
  18543. return;
  18544. }
  18545. this._scene.getEngine().clear(null, false, depth, stencil);
  18546. this._depthStencilBufferAlreadyCleaned = true;
  18547. };
  18548. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18549. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18550. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18551. var info = null;
  18552. if (observable) {
  18553. if (!this._renderinGroupInfo) {
  18554. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18555. }
  18556. info = this._renderinGroupInfo;
  18557. info.scene = this._scene;
  18558. info.camera = this._scene.activeCamera;
  18559. }
  18560. // Dispatch sprites
  18561. if (renderSprites) {
  18562. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18563. var manager = this._scene.spriteManagers[index];
  18564. this.dispatchSprites(manager);
  18565. }
  18566. }
  18567. // Render
  18568. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18569. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18570. var renderingGroup = this._renderingGroups[index];
  18571. if (!renderingGroup && !observable)
  18572. continue;
  18573. var renderingGroupMask = 0;
  18574. // Fire PRECLEAR stage
  18575. if (observable && info) {
  18576. renderingGroupMask = Math.pow(2, index);
  18577. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18578. info.renderingGroupId = index;
  18579. observable.notifyObservers(info, renderingGroupMask);
  18580. }
  18581. // Clear depth/stencil if needed
  18582. if (RenderingManager.AUTOCLEAR) {
  18583. var autoClear = this._autoClearDepthStencil[index];
  18584. if (autoClear && autoClear.autoClear) {
  18585. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18586. }
  18587. }
  18588. if (observable && info) {
  18589. // Fire PREOPAQUE stage
  18590. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18591. observable.notifyObservers(info, renderingGroupMask);
  18592. // Fire PRETRANSPARENT stage
  18593. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18594. observable.notifyObservers(info, renderingGroupMask);
  18595. }
  18596. if (renderingGroup)
  18597. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18598. // Fire POSTTRANSPARENT stage
  18599. if (observable && info) {
  18600. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18601. observable.notifyObservers(info, renderingGroupMask);
  18602. }
  18603. }
  18604. };
  18605. RenderingManager.prototype.reset = function () {
  18606. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18607. var renderingGroup = this._renderingGroups[index];
  18608. if (renderingGroup) {
  18609. renderingGroup.prepare();
  18610. }
  18611. }
  18612. };
  18613. RenderingManager.prototype.dispose = function () {
  18614. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18615. var renderingGroup = this._renderingGroups[index];
  18616. if (renderingGroup) {
  18617. renderingGroup.dispose();
  18618. }
  18619. }
  18620. this._renderingGroups.length = 0;
  18621. };
  18622. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18623. if (this._renderingGroups[renderingGroupId] === undefined) {
  18624. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18625. }
  18626. };
  18627. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18628. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18629. this._prepareRenderingGroup(renderingGroupId);
  18630. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18631. };
  18632. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18633. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18634. this._prepareRenderingGroup(renderingGroupId);
  18635. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18636. };
  18637. /**
  18638. * @param subMesh The submesh to dispatch
  18639. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18640. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18641. */
  18642. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18643. if (mesh === undefined) {
  18644. mesh = subMesh.getMesh();
  18645. }
  18646. var renderingGroupId = mesh.renderingGroupId || 0;
  18647. this._prepareRenderingGroup(renderingGroupId);
  18648. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18649. };
  18650. /**
  18651. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18652. * This allowed control for front to back rendering or reversly depending of the special needs.
  18653. *
  18654. * @param renderingGroupId The rendering group id corresponding to its index
  18655. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18656. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18657. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18658. */
  18659. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18660. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18661. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18662. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18663. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18664. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18665. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18666. if (this._renderingGroups[renderingGroupId]) {
  18667. var group = this._renderingGroups[renderingGroupId];
  18668. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18669. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18670. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18671. }
  18672. };
  18673. /**
  18674. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18675. *
  18676. * @param renderingGroupId The rendering group id corresponding to its index
  18677. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18678. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18679. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18680. */
  18681. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18682. if (depth === void 0) { depth = true; }
  18683. if (stencil === void 0) { stencil = true; }
  18684. this._autoClearDepthStencil[renderingGroupId] = {
  18685. autoClear: autoClearDepthStencil,
  18686. depth: depth,
  18687. stencil: stencil
  18688. };
  18689. };
  18690. /**
  18691. * The max id used for rendering groups (not included)
  18692. */
  18693. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18694. /**
  18695. * The min id used for rendering groups (included)
  18696. */
  18697. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18698. /**
  18699. * Used to globally prevent autoclearing scenes.
  18700. */
  18701. RenderingManager.AUTOCLEAR = true;
  18702. return RenderingManager;
  18703. }());
  18704. BABYLON.RenderingManager = RenderingManager;
  18705. })(BABYLON || (BABYLON = {}));
  18706. //# sourceMappingURL=babylon.renderingManager.js.map
  18707. var BABYLON;
  18708. (function (BABYLON) {
  18709. var RenderingGroup = /** @class */ (function () {
  18710. /**
  18711. * Creates a new rendering group.
  18712. * @param index The rendering group index
  18713. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18714. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18715. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18716. */
  18717. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18718. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18719. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18720. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18721. this.index = index;
  18722. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18723. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18724. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18725. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18726. this._particleSystems = new BABYLON.SmartArray(256);
  18727. this._spriteManagers = new BABYLON.SmartArray(256);
  18728. this._edgesRenderers = new BABYLON.SmartArray(16);
  18729. this._scene = scene;
  18730. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18731. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18732. this.transparentSortCompareFn = transparentSortCompareFn;
  18733. }
  18734. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18735. /**
  18736. * Set the opaque sort comparison function.
  18737. * If null the sub meshes will be render in the order they were created
  18738. */
  18739. set: function (value) {
  18740. this._opaqueSortCompareFn = value;
  18741. if (value) {
  18742. this._renderOpaque = this.renderOpaqueSorted;
  18743. }
  18744. else {
  18745. this._renderOpaque = RenderingGroup.renderUnsorted;
  18746. }
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18752. /**
  18753. * Set the alpha test sort comparison function.
  18754. * If null the sub meshes will be render in the order they were created
  18755. */
  18756. set: function (value) {
  18757. this._alphaTestSortCompareFn = value;
  18758. if (value) {
  18759. this._renderAlphaTest = this.renderAlphaTestSorted;
  18760. }
  18761. else {
  18762. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18763. }
  18764. },
  18765. enumerable: true,
  18766. configurable: true
  18767. });
  18768. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18769. /**
  18770. * Set the transparent sort comparison function.
  18771. * If null the sub meshes will be render in the order they were created
  18772. */
  18773. set: function (value) {
  18774. if (value) {
  18775. this._transparentSortCompareFn = value;
  18776. }
  18777. else {
  18778. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18779. }
  18780. this._renderTransparent = this.renderTransparentSorted;
  18781. },
  18782. enumerable: true,
  18783. configurable: true
  18784. });
  18785. /**
  18786. * Render all the sub meshes contained in the group.
  18787. * @param customRenderFunction Used to override the default render behaviour of the group.
  18788. * @returns true if rendered some submeshes.
  18789. */
  18790. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18791. if (customRenderFunction) {
  18792. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18793. return;
  18794. }
  18795. var engine = this._scene.getEngine();
  18796. // Depth only
  18797. if (this._depthOnlySubMeshes.length !== 0) {
  18798. engine.setAlphaTesting(true);
  18799. engine.setColorWrite(false);
  18800. this._renderAlphaTest(this._depthOnlySubMeshes);
  18801. engine.setAlphaTesting(false);
  18802. engine.setColorWrite(true);
  18803. }
  18804. // Opaque
  18805. if (this._opaqueSubMeshes.length !== 0) {
  18806. this._renderOpaque(this._opaqueSubMeshes);
  18807. }
  18808. // Alpha test
  18809. if (this._alphaTestSubMeshes.length !== 0) {
  18810. engine.setAlphaTesting(true);
  18811. this._renderAlphaTest(this._alphaTestSubMeshes);
  18812. engine.setAlphaTesting(false);
  18813. }
  18814. var stencilState = engine.getStencilBuffer();
  18815. engine.setStencilBuffer(false);
  18816. // Sprites
  18817. if (renderSprites) {
  18818. this._renderSprites();
  18819. }
  18820. // Particles
  18821. if (renderParticles) {
  18822. this._renderParticles(activeMeshes);
  18823. }
  18824. if (this.onBeforeTransparentRendering) {
  18825. this.onBeforeTransparentRendering();
  18826. }
  18827. // Transparent
  18828. if (this._transparentSubMeshes.length !== 0) {
  18829. this._renderTransparent(this._transparentSubMeshes);
  18830. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18831. }
  18832. // Set back stencil to false in case it changes before the edge renderer.
  18833. engine.setStencilBuffer(false);
  18834. // Edges
  18835. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18836. this._edgesRenderers.data[edgesRendererIndex].render();
  18837. }
  18838. // Restore Stencil state.
  18839. engine.setStencilBuffer(stencilState);
  18840. };
  18841. /**
  18842. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18843. * @param subMeshes The submeshes to render
  18844. */
  18845. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18846. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18847. };
  18848. /**
  18849. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18850. * @param subMeshes The submeshes to render
  18851. */
  18852. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18853. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18854. };
  18855. /**
  18856. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18857. * @param subMeshes The submeshes to render
  18858. */
  18859. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18860. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18861. };
  18862. /**
  18863. * Renders the submeshes in a specified order.
  18864. * @param subMeshes The submeshes to sort before render
  18865. * @param sortCompareFn The comparison function use to sort
  18866. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18867. * @param transparent Specifies to activate blending if true
  18868. */
  18869. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18870. var subIndex = 0;
  18871. var subMesh;
  18872. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18873. for (; subIndex < subMeshes.length; subIndex++) {
  18874. subMesh = subMeshes.data[subIndex];
  18875. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18876. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18877. }
  18878. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18879. if (sortCompareFn) {
  18880. sortedArray.sort(sortCompareFn);
  18881. }
  18882. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18883. subMesh = sortedArray[subIndex];
  18884. if (transparent) {
  18885. var material = subMesh.getMaterial();
  18886. if (material && material.needDepthPrePass) {
  18887. var engine = material.getScene().getEngine();
  18888. engine.setColorWrite(false);
  18889. engine.setAlphaTesting(true);
  18890. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18891. subMesh.render(false);
  18892. engine.setAlphaTesting(false);
  18893. engine.setColorWrite(true);
  18894. }
  18895. }
  18896. subMesh.render(transparent);
  18897. }
  18898. };
  18899. /**
  18900. * Renders the submeshes in the order they were dispatched (no sort applied).
  18901. * @param subMeshes The submeshes to render
  18902. */
  18903. RenderingGroup.renderUnsorted = function (subMeshes) {
  18904. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18905. var submesh = subMeshes.data[subIndex];
  18906. submesh.render(false);
  18907. }
  18908. };
  18909. /**
  18910. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18911. * are rendered back to front if in the same alpha index.
  18912. *
  18913. * @param a The first submesh
  18914. * @param b The second submesh
  18915. * @returns The result of the comparison
  18916. */
  18917. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18918. // Alpha index first
  18919. if (a._alphaIndex > b._alphaIndex) {
  18920. return 1;
  18921. }
  18922. if (a._alphaIndex < b._alphaIndex) {
  18923. return -1;
  18924. }
  18925. // Then distance to camera
  18926. return RenderingGroup.backToFrontSortCompare(a, b);
  18927. };
  18928. /**
  18929. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18930. * are rendered back to front.
  18931. *
  18932. * @param a The first submesh
  18933. * @param b The second submesh
  18934. * @returns The result of the comparison
  18935. */
  18936. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18937. // Then distance to camera
  18938. if (a._distanceToCamera < b._distanceToCamera) {
  18939. return 1;
  18940. }
  18941. if (a._distanceToCamera > b._distanceToCamera) {
  18942. return -1;
  18943. }
  18944. return 0;
  18945. };
  18946. /**
  18947. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18948. * are rendered front to back (prevent overdraw).
  18949. *
  18950. * @param a The first submesh
  18951. * @param b The second submesh
  18952. * @returns The result of the comparison
  18953. */
  18954. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18955. // Then distance to camera
  18956. if (a._distanceToCamera < b._distanceToCamera) {
  18957. return -1;
  18958. }
  18959. if (a._distanceToCamera > b._distanceToCamera) {
  18960. return 1;
  18961. }
  18962. return 0;
  18963. };
  18964. /**
  18965. * Resets the different lists of submeshes to prepare a new frame.
  18966. */
  18967. RenderingGroup.prototype.prepare = function () {
  18968. this._opaqueSubMeshes.reset();
  18969. this._transparentSubMeshes.reset();
  18970. this._alphaTestSubMeshes.reset();
  18971. this._depthOnlySubMeshes.reset();
  18972. this._particleSystems.reset();
  18973. this._spriteManagers.reset();
  18974. this._edgesRenderers.reset();
  18975. };
  18976. RenderingGroup.prototype.dispose = function () {
  18977. this._opaqueSubMeshes.dispose();
  18978. this._transparentSubMeshes.dispose();
  18979. this._alphaTestSubMeshes.dispose();
  18980. this._depthOnlySubMeshes.dispose();
  18981. this._particleSystems.dispose();
  18982. this._spriteManagers.dispose();
  18983. this._edgesRenderers.dispose();
  18984. };
  18985. /**
  18986. * Inserts the submesh in its correct queue depending on its material.
  18987. * @param subMesh The submesh to dispatch
  18988. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18989. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18990. */
  18991. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18992. // Get mesh and materials if not provided
  18993. if (mesh === undefined) {
  18994. mesh = subMesh.getMesh();
  18995. }
  18996. if (material === undefined) {
  18997. material = subMesh.getMaterial();
  18998. }
  18999. if (material === null || material === undefined) {
  19000. return;
  19001. }
  19002. if (material.needAlphaBlendingForMesh(mesh)) {
  19003. this._transparentSubMeshes.push(subMesh);
  19004. }
  19005. else if (material.needAlphaTesting()) {
  19006. if (material.needDepthPrePass) {
  19007. this._depthOnlySubMeshes.push(subMesh);
  19008. }
  19009. this._alphaTestSubMeshes.push(subMesh);
  19010. }
  19011. else {
  19012. if (material.needDepthPrePass) {
  19013. this._depthOnlySubMeshes.push(subMesh);
  19014. }
  19015. this._opaqueSubMeshes.push(subMesh); // Opaque
  19016. }
  19017. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19018. this._edgesRenderers.push(mesh._edgesRenderer);
  19019. }
  19020. };
  19021. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19022. this._spriteManagers.push(spriteManager);
  19023. };
  19024. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19025. this._particleSystems.push(particleSystem);
  19026. };
  19027. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19028. if (this._particleSystems.length === 0) {
  19029. return;
  19030. }
  19031. // Particles
  19032. var activeCamera = this._scene.activeCamera;
  19033. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19034. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19035. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19036. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19037. continue;
  19038. }
  19039. var emitter = particleSystem.emitter;
  19040. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19041. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19042. }
  19043. }
  19044. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19045. };
  19046. RenderingGroup.prototype._renderSprites = function () {
  19047. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19048. return;
  19049. }
  19050. // Sprites
  19051. var activeCamera = this._scene.activeCamera;
  19052. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19053. for (var id = 0; id < this._spriteManagers.length; id++) {
  19054. var spriteManager = this._spriteManagers.data[id];
  19055. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19056. spriteManager.render();
  19057. }
  19058. }
  19059. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19060. };
  19061. return RenderingGroup;
  19062. }());
  19063. BABYLON.RenderingGroup = RenderingGroup;
  19064. })(BABYLON || (BABYLON = {}));
  19065. //# sourceMappingURL=babylon.renderingGroup.js.map
  19066. var BABYLON;
  19067. (function (BABYLON) {
  19068. var ClickInfo = /** @class */ (function () {
  19069. function ClickInfo() {
  19070. this._singleClick = false;
  19071. this._doubleClick = false;
  19072. this._hasSwiped = false;
  19073. this._ignore = false;
  19074. }
  19075. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19076. get: function () {
  19077. return this._singleClick;
  19078. },
  19079. set: function (b) {
  19080. this._singleClick = b;
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19086. get: function () {
  19087. return this._doubleClick;
  19088. },
  19089. set: function (b) {
  19090. this._doubleClick = b;
  19091. },
  19092. enumerable: true,
  19093. configurable: true
  19094. });
  19095. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19096. get: function () {
  19097. return this._hasSwiped;
  19098. },
  19099. set: function (b) {
  19100. this._hasSwiped = b;
  19101. },
  19102. enumerable: true,
  19103. configurable: true
  19104. });
  19105. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19106. get: function () {
  19107. return this._ignore;
  19108. },
  19109. set: function (b) {
  19110. this._ignore = b;
  19111. },
  19112. enumerable: true,
  19113. configurable: true
  19114. });
  19115. return ClickInfo;
  19116. }());
  19117. /**
  19118. * This class is used by the onRenderingGroupObservable
  19119. */
  19120. var RenderingGroupInfo = /** @class */ (function () {
  19121. function RenderingGroupInfo() {
  19122. }
  19123. /**
  19124. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19125. * This stage will be fired no matter what
  19126. */
  19127. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19128. /**
  19129. * Called before opaque object are rendered.
  19130. * This stage will be fired only if there's 3D Opaque content to render
  19131. */
  19132. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19133. /**
  19134. * Called after the opaque objects are rendered and before the transparent ones
  19135. * This stage will be fired only if there's 3D transparent content to render
  19136. */
  19137. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19138. /**
  19139. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19140. * This stage will be fired no matter what
  19141. */
  19142. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19143. return RenderingGroupInfo;
  19144. }());
  19145. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19146. /**
  19147. * Represents a scene to be rendered by the engine.
  19148. * @see http://doc.babylonjs.com/page.php?p=21911
  19149. */
  19150. var Scene = /** @class */ (function () {
  19151. /**
  19152. * @constructor
  19153. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19154. */
  19155. function Scene(engine) {
  19156. // Members
  19157. this.autoClear = true;
  19158. this.autoClearDepthAndStencil = true;
  19159. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19160. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19161. this.forceWireframe = false;
  19162. this._forcePointsCloud = false;
  19163. this.forceShowBoundingBoxes = false;
  19164. this.animationsEnabled = true;
  19165. this.useConstantAnimationDeltaTime = false;
  19166. this.constantlyUpdateMeshUnderPointer = false;
  19167. this.hoverCursor = "pointer";
  19168. this.defaultCursor = "";
  19169. /**
  19170. * This is used to call preventDefault() on pointer down
  19171. * in order to block unwanted artifacts like system double clicks
  19172. */
  19173. this.preventDefaultOnPointerDown = true;
  19174. // Metadata
  19175. this.metadata = null;
  19176. /**
  19177. * An event triggered when the scene is disposed.
  19178. * @type {BABYLON.Observable}
  19179. */
  19180. this.onDisposeObservable = new BABYLON.Observable();
  19181. /**
  19182. * An event triggered before rendering the scene (right after animations and physics)
  19183. * @type {BABYLON.Observable}
  19184. */
  19185. this.onBeforeRenderObservable = new BABYLON.Observable();
  19186. /**
  19187. * An event triggered after rendering the scene
  19188. * @type {BABYLON.Observable}
  19189. */
  19190. this.onAfterRenderObservable = new BABYLON.Observable();
  19191. /**
  19192. * An event triggered before animating the scene
  19193. * @type {BABYLON.Observable}
  19194. */
  19195. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19196. /**
  19197. * An event triggered after animations processing
  19198. * @type {BABYLON.Observable}
  19199. */
  19200. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19201. /**
  19202. * An event triggered before draw calls are ready to be sent
  19203. * @type {BABYLON.Observable}
  19204. */
  19205. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19206. /**
  19207. * An event triggered after draw calls have been sent
  19208. * @type {BABYLON.Observable}
  19209. */
  19210. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19211. /**
  19212. * An event triggered when physic simulation is about to be run
  19213. * @type {BABYLON.Observable}
  19214. */
  19215. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19216. /**
  19217. * An event triggered when physic simulation has been done
  19218. * @type {BABYLON.Observable}
  19219. */
  19220. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19221. /**
  19222. * An event triggered when the scene is ready
  19223. * @type {BABYLON.Observable}
  19224. */
  19225. this.onReadyObservable = new BABYLON.Observable();
  19226. /**
  19227. * An event triggered before rendering a camera
  19228. * @type {BABYLON.Observable}
  19229. */
  19230. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19231. /**
  19232. * An event triggered after rendering a camera
  19233. * @type {BABYLON.Observable}
  19234. */
  19235. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19236. /**
  19237. * An event triggered when active meshes evaluation is about to start
  19238. * @type {BABYLON.Observable}
  19239. */
  19240. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19241. /**
  19242. * An event triggered when active meshes evaluation is done
  19243. * @type {BABYLON.Observable}
  19244. */
  19245. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19246. /**
  19247. * An event triggered when particles rendering is about to start
  19248. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19249. * @type {BABYLON.Observable}
  19250. */
  19251. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19252. /**
  19253. * An event triggered when particles rendering is done
  19254. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19255. * @type {BABYLON.Observable}
  19256. */
  19257. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19258. /**
  19259. * An event triggered when sprites rendering is about to start
  19260. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19261. * @type {BABYLON.Observable}
  19262. */
  19263. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19264. /**
  19265. * An event triggered when sprites rendering is done
  19266. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19267. * @type {BABYLON.Observable}
  19268. */
  19269. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19270. /**
  19271. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19272. * @type {BABYLON.Observable}
  19273. */
  19274. this.onDataLoadedObservable = new BABYLON.Observable();
  19275. /**
  19276. * An event triggered when a camera is created
  19277. * @type {BABYLON.Observable}
  19278. */
  19279. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19280. /**
  19281. * An event triggered when a camera is removed
  19282. * @type {BABYLON.Observable}
  19283. */
  19284. this.onCameraRemovedObservable = new BABYLON.Observable();
  19285. /**
  19286. * An event triggered when a light is created
  19287. * @type {BABYLON.Observable}
  19288. */
  19289. this.onNewLightAddedObservable = new BABYLON.Observable();
  19290. /**
  19291. * An event triggered when a light is removed
  19292. * @type {BABYLON.Observable}
  19293. */
  19294. this.onLightRemovedObservable = new BABYLON.Observable();
  19295. /**
  19296. * An event triggered when a geometry is created
  19297. * @type {BABYLON.Observable}
  19298. */
  19299. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19300. /**
  19301. * An event triggered when a geometry is removed
  19302. * @type {BABYLON.Observable}
  19303. */
  19304. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19305. /**
  19306. * An event triggered when a transform node is created
  19307. * @type {BABYLON.Observable}
  19308. */
  19309. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19310. /**
  19311. * An event triggered when a transform node is removed
  19312. * @type {BABYLON.Observable}
  19313. */
  19314. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19315. /**
  19316. * An event triggered when a mesh is created
  19317. * @type {BABYLON.Observable}
  19318. */
  19319. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19320. /**
  19321. * An event triggered when a mesh is removed
  19322. * @type {BABYLON.Observable}
  19323. */
  19324. this.onMeshRemovedObservable = new BABYLON.Observable();
  19325. /**
  19326. * An event triggered when render targets are about to be rendered
  19327. * Can happen multiple times per frame.
  19328. * @type {BABYLON.Observable}
  19329. */
  19330. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19331. /**
  19332. * An event triggered when render targets were rendered.
  19333. * Can happen multiple times per frame.
  19334. * @type {BABYLON.Observable}
  19335. */
  19336. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19337. /**
  19338. * An event triggered before calculating deterministic simulation step
  19339. * @type {BABYLON.Observable}
  19340. */
  19341. this.onBeforeStepObservable = new BABYLON.Observable();
  19342. /**
  19343. * An event triggered after calculating deterministic simulation step
  19344. * @type {BABYLON.Observable}
  19345. */
  19346. this.onAfterStepObservable = new BABYLON.Observable();
  19347. /**
  19348. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19349. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19350. * 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)
  19351. */
  19352. this.onRenderingGroupObservable = new BABYLON.Observable();
  19353. // Animations
  19354. this.animations = [];
  19355. /**
  19356. * 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).
  19357. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19358. */
  19359. this.onPrePointerObservable = new BABYLON.Observable();
  19360. /**
  19361. * Observable event triggered each time an input event is received from the rendering canvas
  19362. */
  19363. this.onPointerObservable = new BABYLON.Observable();
  19364. this._meshPickProceed = false;
  19365. this._currentPickResult = null;
  19366. this._previousPickResult = null;
  19367. this._totalPointersPressed = 0;
  19368. this._doubleClickOccured = false;
  19369. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19370. this.cameraToUseForPointers = null;
  19371. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19372. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19373. this._startingPointerTime = 0;
  19374. this._previousStartingPointerTime = 0;
  19375. // Deterministic lockstep
  19376. this._timeAccumulator = 0;
  19377. this._currentStepId = 0;
  19378. this._currentInternalStep = 0;
  19379. // Keyboard
  19380. /**
  19381. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19382. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19383. */
  19384. this.onPreKeyboardObservable = new BABYLON.Observable();
  19385. /**
  19386. * Observable event triggered each time an keyboard event is received from the hosting window
  19387. */
  19388. this.onKeyboardObservable = new BABYLON.Observable();
  19389. // Coordinate system
  19390. /**
  19391. * use right-handed coordinate system on this scene.
  19392. * @type {boolean}
  19393. */
  19394. this._useRightHandedSystem = false;
  19395. // Fog
  19396. this._fogEnabled = true;
  19397. this._fogMode = Scene.FOGMODE_NONE;
  19398. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19399. this.fogDensity = 0.1;
  19400. this.fogStart = 0;
  19401. this.fogEnd = 1000.0;
  19402. // Lights
  19403. /**
  19404. * is shadow enabled on this scene.
  19405. * @type {boolean}
  19406. */
  19407. this._shadowsEnabled = true;
  19408. /**
  19409. * is light enabled on this scene.
  19410. * @type {boolean}
  19411. */
  19412. this._lightsEnabled = true;
  19413. /**
  19414. * All of the lights added to this scene.
  19415. * @see BABYLON.Light
  19416. * @type {BABYLON.Light[]}
  19417. */
  19418. this.lights = new Array();
  19419. // Cameras
  19420. /** All of the cameras added to this scene. */
  19421. this.cameras = new Array();
  19422. /** All of the active cameras added to this scene. */
  19423. this.activeCameras = new Array();
  19424. // Meshes
  19425. /**
  19426. * All of the tranform nodes added to this scene.
  19427. * @see BABYLON.TransformNode
  19428. * @type {BABYLON.TransformNode[]}
  19429. */
  19430. this.transformNodes = new Array();
  19431. /**
  19432. * All of the (abstract) meshes added to this scene.
  19433. * @see BABYLON.AbstractMesh
  19434. * @type {BABYLON.AbstractMesh[]}
  19435. */
  19436. this.meshes = new Array();
  19437. /**
  19438. * All of the animation groups added to this scene.
  19439. * @see BABYLON.AnimationGroup
  19440. * @type {BABYLON.AnimationGroup[]}
  19441. */
  19442. this.animationGroups = new Array();
  19443. // Geometries
  19444. this._geometries = new Array();
  19445. this.materials = new Array();
  19446. this.multiMaterials = new Array();
  19447. // Textures
  19448. this._texturesEnabled = true;
  19449. this.textures = new Array();
  19450. // Particles
  19451. this.particlesEnabled = true;
  19452. this.particleSystems = new Array();
  19453. // Sprites
  19454. this.spritesEnabled = true;
  19455. this.spriteManagers = new Array();
  19456. // Layers
  19457. this.layers = new Array();
  19458. this.highlightLayers = new Array();
  19459. // Skeletons
  19460. this._skeletonsEnabled = true;
  19461. this.skeletons = new Array();
  19462. // Morph targets
  19463. this.morphTargetManagers = new Array();
  19464. // Lens flares
  19465. this.lensFlaresEnabled = true;
  19466. this.lensFlareSystems = new Array();
  19467. // Collisions
  19468. this.collisionsEnabled = true;
  19469. /** Defines the gravity applied to this scene */
  19470. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19471. // Postprocesses
  19472. this.postProcesses = new Array();
  19473. this.postProcessesEnabled = true;
  19474. // Customs render targets
  19475. this.renderTargetsEnabled = true;
  19476. this.dumpNextRenderTargets = false;
  19477. this.customRenderTargets = new Array();
  19478. // Imported meshes
  19479. this.importedMeshesFiles = new Array();
  19480. // Probes
  19481. this.probesEnabled = true;
  19482. this.reflectionProbes = new Array();
  19483. this._actionManagers = new Array();
  19484. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19485. // Procedural textures
  19486. this.proceduralTexturesEnabled = true;
  19487. this._proceduralTextures = new Array();
  19488. this.soundTracks = new Array();
  19489. this._audioEnabled = true;
  19490. this._headphone = false;
  19491. // Performance counters
  19492. this._totalVertices = new BABYLON.PerfCounter();
  19493. this._activeIndices = new BABYLON.PerfCounter();
  19494. this._activeParticles = new BABYLON.PerfCounter();
  19495. this._activeBones = new BABYLON.PerfCounter();
  19496. this._animationTime = 0;
  19497. this.animationTimeScale = 1;
  19498. this._renderId = 0;
  19499. this._executeWhenReadyTimeoutId = -1;
  19500. this._intermediateRendering = false;
  19501. this._viewUpdateFlag = -1;
  19502. this._projectionUpdateFlag = -1;
  19503. this._alternateViewUpdateFlag = -1;
  19504. this._alternateProjectionUpdateFlag = -1;
  19505. this._toBeDisposed = new BABYLON.SmartArray(256);
  19506. this._activeRequests = new Array();
  19507. this._pendingData = new Array();
  19508. this._isDisposed = false;
  19509. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19510. this._activeMeshes = new BABYLON.SmartArray(256);
  19511. this._processedMaterials = new BABYLON.SmartArray(256);
  19512. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19513. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19514. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19515. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19516. this._activeAnimatables = new Array();
  19517. this._transformMatrix = BABYLON.Matrix.Zero();
  19518. this._useAlternateCameraConfiguration = false;
  19519. this._alternateRendering = false;
  19520. this.requireLightSorting = false;
  19521. this._activeMeshesFrozen = false;
  19522. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19523. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19524. this._engine.scenes.push(this);
  19525. this._uid = null;
  19526. this._renderingManager = new BABYLON.RenderingManager(this);
  19527. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19528. if (BABYLON.OutlineRenderer) {
  19529. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19530. }
  19531. if (BABYLON.Tools.IsWindowObjectExist()) {
  19532. this.attachControl();
  19533. }
  19534. //simplification queue
  19535. if (BABYLON.SimplificationQueue) {
  19536. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19537. }
  19538. //collision coordinator initialization. For now legacy per default.
  19539. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19540. // Uniform Buffer
  19541. this._createUbo();
  19542. // Default Image processing definition.
  19543. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19544. }
  19545. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19546. /** The fog is deactivated */
  19547. get: function () {
  19548. return Scene._FOGMODE_NONE;
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19554. /** The fog density is following an exponential function */
  19555. get: function () {
  19556. return Scene._FOGMODE_EXP;
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19562. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19563. get: function () {
  19564. return Scene._FOGMODE_EXP2;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19570. /** The fog density is following a linear function. */
  19571. get: function () {
  19572. return Scene._FOGMODE_LINEAR;
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19578. /**
  19579. * Texture used in all pbr material as the reflection texture.
  19580. * As in the majority of the scene they are the same (exception for multi room and so on),
  19581. * this is easier to reference from here than from all the materials.
  19582. */
  19583. get: function () {
  19584. return this._environmentTexture;
  19585. },
  19586. /**
  19587. * Texture used in all pbr material as the reflection texture.
  19588. * As in the majority of the scene they are the same (exception for multi room and so on),
  19589. * this is easier to set here than in all the materials.
  19590. */
  19591. set: function (value) {
  19592. if (this._environmentTexture === value) {
  19593. return;
  19594. }
  19595. this._environmentTexture = value;
  19596. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19602. /**
  19603. * Default image processing configuration used either in the rendering
  19604. * Forward main pass or through the imageProcessingPostProcess if present.
  19605. * As in the majority of the scene they are the same (exception for multi camera),
  19606. * this is easier to reference from here than from all the materials and post process.
  19607. *
  19608. * No setter as we it is a shared configuration, you can set the values instead.
  19609. */
  19610. get: function () {
  19611. return this._imageProcessingConfiguration;
  19612. },
  19613. enumerable: true,
  19614. configurable: true
  19615. });
  19616. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19617. get: function () {
  19618. return this._forcePointsCloud;
  19619. },
  19620. set: function (value) {
  19621. if (this._forcePointsCloud === value) {
  19622. return;
  19623. }
  19624. this._forcePointsCloud = value;
  19625. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(Scene.prototype, "onDispose", {
  19631. /** A function to be executed when this scene is disposed. */
  19632. set: function (callback) {
  19633. if (this._onDisposeObserver) {
  19634. this.onDisposeObservable.remove(this._onDisposeObserver);
  19635. }
  19636. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19637. },
  19638. enumerable: true,
  19639. configurable: true
  19640. });
  19641. Object.defineProperty(Scene.prototype, "beforeRender", {
  19642. /** A function to be executed before rendering this scene */
  19643. set: function (callback) {
  19644. if (this._onBeforeRenderObserver) {
  19645. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19646. }
  19647. if (callback) {
  19648. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19649. }
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(Scene.prototype, "afterRender", {
  19655. /** A function to be executed after rendering this scene */
  19656. set: function (callback) {
  19657. if (this._onAfterRenderObserver) {
  19658. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19659. }
  19660. if (callback) {
  19661. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19662. }
  19663. },
  19664. enumerable: true,
  19665. configurable: true
  19666. });
  19667. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19668. set: function (callback) {
  19669. if (this._onBeforeCameraRenderObserver) {
  19670. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19671. }
  19672. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19678. set: function (callback) {
  19679. if (this._onAfterCameraRenderObserver) {
  19680. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19681. }
  19682. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19683. },
  19684. enumerable: true,
  19685. configurable: true
  19686. });
  19687. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19688. get: function () {
  19689. if (!this._gamepadManager) {
  19690. this._gamepadManager = new BABYLON.GamepadManager(this);
  19691. }
  19692. return this._gamepadManager;
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19698. get: function () {
  19699. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19700. },
  19701. enumerable: true,
  19702. configurable: true
  19703. });
  19704. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19705. get: function () {
  19706. return this._useRightHandedSystem;
  19707. },
  19708. set: function (value) {
  19709. if (this._useRightHandedSystem === value) {
  19710. return;
  19711. }
  19712. this._useRightHandedSystem = value;
  19713. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Scene.prototype.setStepId = function (newStepId) {
  19719. this._currentStepId = newStepId;
  19720. };
  19721. ;
  19722. Scene.prototype.getStepId = function () {
  19723. return this._currentStepId;
  19724. };
  19725. ;
  19726. Scene.prototype.getInternalStep = function () {
  19727. return this._currentInternalStep;
  19728. };
  19729. ;
  19730. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19731. get: function () {
  19732. return this._fogEnabled;
  19733. },
  19734. /**
  19735. * is fog enabled on this scene.
  19736. */
  19737. set: function (value) {
  19738. if (this._fogEnabled === value) {
  19739. return;
  19740. }
  19741. this._fogEnabled = value;
  19742. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(Scene.prototype, "fogMode", {
  19748. get: function () {
  19749. return this._fogMode;
  19750. },
  19751. set: function (value) {
  19752. if (this._fogMode === value) {
  19753. return;
  19754. }
  19755. this._fogMode = value;
  19756. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19762. get: function () {
  19763. return this._shadowsEnabled;
  19764. },
  19765. set: function (value) {
  19766. if (this._shadowsEnabled === value) {
  19767. return;
  19768. }
  19769. this._shadowsEnabled = value;
  19770. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19776. get: function () {
  19777. return this._lightsEnabled;
  19778. },
  19779. set: function (value) {
  19780. if (this._lightsEnabled === value) {
  19781. return;
  19782. }
  19783. this._lightsEnabled = value;
  19784. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19790. /** The default material used on meshes when no material is affected */
  19791. get: function () {
  19792. if (!this._defaultMaterial) {
  19793. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19794. }
  19795. return this._defaultMaterial;
  19796. },
  19797. /** The default material used on meshes when no material is affected */
  19798. set: function (value) {
  19799. this._defaultMaterial = value;
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19805. get: function () {
  19806. return this._texturesEnabled;
  19807. },
  19808. set: function (value) {
  19809. if (this._texturesEnabled === value) {
  19810. return;
  19811. }
  19812. this._texturesEnabled = value;
  19813. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19819. get: function () {
  19820. return this._skeletonsEnabled;
  19821. },
  19822. set: function (value) {
  19823. if (this._skeletonsEnabled === value) {
  19824. return;
  19825. }
  19826. this._skeletonsEnabled = value;
  19827. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19833. get: function () {
  19834. if (!this._postProcessRenderPipelineManager) {
  19835. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19836. }
  19837. return this._postProcessRenderPipelineManager;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19843. get: function () {
  19844. if (!this._mainSoundTrack) {
  19845. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19846. }
  19847. return this._mainSoundTrack;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19853. get: function () {
  19854. return this._alternateRendering;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19860. get: function () {
  19861. return this._frustumPlanes;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(Scene.prototype, "debugLayer", {
  19867. // Properties
  19868. get: function () {
  19869. if (!this._debugLayer) {
  19870. this._debugLayer = new BABYLON.DebugLayer(this);
  19871. }
  19872. return this._debugLayer;
  19873. },
  19874. enumerable: true,
  19875. configurable: true
  19876. });
  19877. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19878. get: function () {
  19879. return this._workerCollisions;
  19880. },
  19881. set: function (enabled) {
  19882. if (!BABYLON.CollisionCoordinatorLegacy) {
  19883. return;
  19884. }
  19885. enabled = (enabled && !!Worker);
  19886. this._workerCollisions = enabled;
  19887. if (this.collisionCoordinator) {
  19888. this.collisionCoordinator.destroy();
  19889. }
  19890. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19891. this.collisionCoordinator.init(this);
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19897. get: function () {
  19898. return this._selectionOctree;
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19904. /**
  19905. * The mesh that is currently under the pointer.
  19906. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19907. */
  19908. get: function () {
  19909. return this._pointerOverMesh;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Scene.prototype, "pointerX", {
  19915. /**
  19916. * Current on-screen X position of the pointer
  19917. * @return {number} X position of the pointer
  19918. */
  19919. get: function () {
  19920. return this._pointerX;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(Scene.prototype, "pointerY", {
  19926. /**
  19927. * Current on-screen Y position of the pointer
  19928. * @return {number} Y position of the pointer
  19929. */
  19930. get: function () {
  19931. return this._pointerY;
  19932. },
  19933. enumerable: true,
  19934. configurable: true
  19935. });
  19936. Scene.prototype.getCachedMaterial = function () {
  19937. return this._cachedMaterial;
  19938. };
  19939. Scene.prototype.getCachedEffect = function () {
  19940. return this._cachedEffect;
  19941. };
  19942. Scene.prototype.getCachedVisibility = function () {
  19943. return this._cachedVisibility;
  19944. };
  19945. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19946. if (visibility === void 0) { visibility = 1; }
  19947. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19948. };
  19949. Scene.prototype.getBoundingBoxRenderer = function () {
  19950. if (!this._boundingBoxRenderer) {
  19951. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19952. }
  19953. return this._boundingBoxRenderer;
  19954. };
  19955. Scene.prototype.getOutlineRenderer = function () {
  19956. return this._outlineRenderer;
  19957. };
  19958. Scene.prototype.getEngine = function () {
  19959. return this._engine;
  19960. };
  19961. Scene.prototype.getTotalVertices = function () {
  19962. return this._totalVertices.current;
  19963. };
  19964. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19965. get: function () {
  19966. return this._totalVertices;
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. Scene.prototype.getActiveIndices = function () {
  19972. return this._activeIndices.current;
  19973. };
  19974. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19975. get: function () {
  19976. return this._activeIndices;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Scene.prototype.getActiveParticles = function () {
  19982. return this._activeParticles.current;
  19983. };
  19984. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19985. get: function () {
  19986. return this._activeParticles;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Scene.prototype.getActiveBones = function () {
  19992. return this._activeBones.current;
  19993. };
  19994. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19995. get: function () {
  19996. return this._activeBones;
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. // Stats
  20002. Scene.prototype.getInterFramePerfCounter = function () {
  20003. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20004. return 0;
  20005. };
  20006. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20007. get: function () {
  20008. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20009. return null;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Scene.prototype.getLastFrameDuration = function () {
  20015. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20016. return 0;
  20017. };
  20018. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20019. get: function () {
  20020. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20021. return null;
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20027. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20028. return 0;
  20029. };
  20030. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20031. get: function () {
  20032. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20033. return null;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Scene.prototype.getActiveMeshes = function () {
  20039. return this._activeMeshes;
  20040. };
  20041. Scene.prototype.getRenderTargetsDuration = function () {
  20042. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20043. return 0;
  20044. };
  20045. Scene.prototype.getRenderDuration = function () {
  20046. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20047. return 0;
  20048. };
  20049. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20050. get: function () {
  20051. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20052. return null;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. Scene.prototype.getParticlesDuration = function () {
  20058. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20059. return 0;
  20060. };
  20061. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20062. get: function () {
  20063. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20064. return null;
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. Scene.prototype.getSpritesDuration = function () {
  20070. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20071. return 0;
  20072. };
  20073. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20074. get: function () {
  20075. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20076. return null;
  20077. },
  20078. enumerable: true,
  20079. configurable: true
  20080. });
  20081. Scene.prototype.getAnimationRatio = function () {
  20082. return this._animationRatio;
  20083. };
  20084. Scene.prototype.getRenderId = function () {
  20085. return this._renderId;
  20086. };
  20087. Scene.prototype.incrementRenderId = function () {
  20088. this._renderId++;
  20089. };
  20090. Scene.prototype._updatePointerPosition = function (evt) {
  20091. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20092. if (!canvasRect) {
  20093. return;
  20094. }
  20095. this._pointerX = evt.clientX - canvasRect.left;
  20096. this._pointerY = evt.clientY - canvasRect.top;
  20097. this._unTranslatedPointerX = this._pointerX;
  20098. this._unTranslatedPointerY = this._pointerY;
  20099. };
  20100. Scene.prototype._createUbo = function () {
  20101. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20102. this._sceneUbo.addUniform("viewProjection", 16);
  20103. this._sceneUbo.addUniform("view", 16);
  20104. };
  20105. Scene.prototype._createAlternateUbo = function () {
  20106. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20107. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20108. this._alternateSceneUbo.addUniform("view", 16);
  20109. };
  20110. // Pointers handling
  20111. /**
  20112. * Use this method to simulate a pointer move on a mesh
  20113. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20114. */
  20115. Scene.prototype.simulatePointerMove = function (pickResult) {
  20116. var evt = new PointerEvent("pointermove");
  20117. return this._processPointerMove(pickResult, evt);
  20118. };
  20119. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20120. var canvas = this._engine.getRenderingCanvas();
  20121. if (!canvas) {
  20122. return this;
  20123. }
  20124. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20125. this.setPointerOverSprite(null);
  20126. this.setPointerOverMesh(pickResult.pickedMesh);
  20127. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20128. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20129. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20130. }
  20131. else {
  20132. canvas.style.cursor = this.hoverCursor;
  20133. }
  20134. }
  20135. else {
  20136. canvas.style.cursor = this.defaultCursor;
  20137. }
  20138. }
  20139. else {
  20140. this.setPointerOverMesh(null);
  20141. // Sprites
  20142. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20143. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20144. this.setPointerOverSprite(pickResult.pickedSprite);
  20145. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20146. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20147. }
  20148. else {
  20149. canvas.style.cursor = this.hoverCursor;
  20150. }
  20151. }
  20152. else {
  20153. this.setPointerOverSprite(null);
  20154. // Restore pointer
  20155. canvas.style.cursor = this.defaultCursor;
  20156. }
  20157. }
  20158. if (pickResult) {
  20159. if (this.onPointerMove) {
  20160. this.onPointerMove(evt, pickResult);
  20161. }
  20162. if (this.onPointerObservable.hasObservers()) {
  20163. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20164. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20165. this.onPointerObservable.notifyObservers(pi, type);
  20166. }
  20167. }
  20168. return this;
  20169. };
  20170. /**
  20171. * Use this method to simulate a pointer down on a mesh
  20172. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20173. */
  20174. Scene.prototype.simulatePointerDown = function (pickResult) {
  20175. var evt = new PointerEvent("pointerdown");
  20176. return this._processPointerDown(pickResult, evt);
  20177. };
  20178. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20179. var _this = this;
  20180. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20181. this._pickedDownMesh = pickResult.pickedMesh;
  20182. var actionManager = pickResult.pickedMesh.actionManager;
  20183. if (actionManager) {
  20184. if (actionManager.hasPickTriggers) {
  20185. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20186. switch (evt.button) {
  20187. case 0:
  20188. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20189. break;
  20190. case 1:
  20191. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20192. break;
  20193. case 2:
  20194. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20195. break;
  20196. }
  20197. }
  20198. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20199. window.setTimeout(function () {
  20200. 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);
  20201. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20202. if (_this._totalPointersPressed !== 0 &&
  20203. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20204. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20205. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20206. _this._startingPointerTime = 0;
  20207. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20208. }
  20209. }
  20210. }, Scene.LongPressDelay);
  20211. }
  20212. }
  20213. }
  20214. if (pickResult) {
  20215. if (this.onPointerDown) {
  20216. this.onPointerDown(evt, pickResult);
  20217. }
  20218. if (this.onPointerObservable.hasObservers()) {
  20219. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20220. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20221. this.onPointerObservable.notifyObservers(pi, type);
  20222. }
  20223. }
  20224. return this;
  20225. };
  20226. /**
  20227. * Use this method to simulate a pointer up on a mesh
  20228. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20229. */
  20230. Scene.prototype.simulatePointerUp = function (pickResult) {
  20231. var evt = new PointerEvent("pointerup");
  20232. var clickInfo = new ClickInfo();
  20233. clickInfo.singleClick = true;
  20234. clickInfo.ignore = true;
  20235. return this._processPointerUp(pickResult, evt, clickInfo);
  20236. };
  20237. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20238. if (pickResult && pickResult && pickResult.pickedMesh) {
  20239. this._pickedUpMesh = pickResult.pickedMesh;
  20240. if (this._pickedDownMesh === this._pickedUpMesh) {
  20241. if (this.onPointerPick) {
  20242. this.onPointerPick(evt, pickResult);
  20243. }
  20244. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20245. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20246. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20247. this.onPointerObservable.notifyObservers(pi, type);
  20248. }
  20249. }
  20250. if (pickResult.pickedMesh.actionManager) {
  20251. if (clickInfo.ignore) {
  20252. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20253. }
  20254. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20255. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20256. }
  20257. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20258. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20259. }
  20260. }
  20261. }
  20262. if (this._pickedDownMesh &&
  20263. this._pickedDownMesh.actionManager &&
  20264. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20265. this._pickedDownMesh !== this._pickedUpMesh) {
  20266. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20267. }
  20268. if (this.onPointerUp) {
  20269. this.onPointerUp(evt, pickResult);
  20270. }
  20271. if (this.onPointerObservable.hasObservers()) {
  20272. if (!clickInfo.ignore) {
  20273. if (!clickInfo.hasSwiped) {
  20274. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20275. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20276. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20277. this.onPointerObservable.notifyObservers(pi, type);
  20278. }
  20279. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20280. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20281. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20282. this.onPointerObservable.notifyObservers(pi, type);
  20283. }
  20284. }
  20285. }
  20286. else {
  20287. var type = BABYLON.PointerEventTypes.POINTERUP;
  20288. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20289. this.onPointerObservable.notifyObservers(pi, type);
  20290. }
  20291. }
  20292. return this;
  20293. };
  20294. /**
  20295. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20296. * @param attachUp defines if you want to attach events to pointerup
  20297. * @param attachDown defines if you want to attach events to pointerdown
  20298. * @param attachMove defines if you want to attach events to pointermove
  20299. */
  20300. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20301. var _this = this;
  20302. if (attachUp === void 0) { attachUp = true; }
  20303. if (attachDown === void 0) { attachDown = true; }
  20304. if (attachMove === void 0) { attachMove = true; }
  20305. this._initActionManager = function (act, clickInfo) {
  20306. if (!_this._meshPickProceed) {
  20307. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20308. _this._currentPickResult = pickResult;
  20309. if (pickResult) {
  20310. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20311. }
  20312. _this._meshPickProceed = true;
  20313. }
  20314. return act;
  20315. };
  20316. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20317. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20318. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20319. btn !== _this._previousButtonPressed) {
  20320. _this._doubleClickOccured = false;
  20321. clickInfo.singleClick = true;
  20322. clickInfo.ignore = false;
  20323. cb(clickInfo, _this._currentPickResult);
  20324. }
  20325. };
  20326. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20327. var clickInfo = new ClickInfo();
  20328. _this._currentPickResult = null;
  20329. var act = null;
  20330. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20331. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20332. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20333. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20334. act = _this._initActionManager(act, clickInfo);
  20335. if (act)
  20336. checkPicking = act.hasPickTriggers;
  20337. }
  20338. if (checkPicking) {
  20339. var btn = evt.button;
  20340. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20341. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20342. if (!clickInfo.hasSwiped) {
  20343. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20344. if (!checkSingleClickImmediately) {
  20345. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20346. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20347. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20348. act = _this._initActionManager(act, clickInfo);
  20349. if (act)
  20350. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20351. }
  20352. }
  20353. if (checkSingleClickImmediately) {
  20354. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20355. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20356. btn !== _this._previousButtonPressed) {
  20357. clickInfo.singleClick = true;
  20358. cb(clickInfo, _this._currentPickResult);
  20359. }
  20360. }
  20361. else {
  20362. // wait that no double click has been raised during the double click delay
  20363. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20364. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20365. }
  20366. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20367. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20368. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20369. act = _this._initActionManager(act, clickInfo);
  20370. if (act)
  20371. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20372. }
  20373. if (checkDoubleClick) {
  20374. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20375. if (btn === _this._previousButtonPressed &&
  20376. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20377. !_this._doubleClickOccured) {
  20378. // pointer has not moved for 2 clicks, it's a double click
  20379. if (!clickInfo.hasSwiped &&
  20380. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20381. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20382. _this._previousStartingPointerTime = 0;
  20383. _this._doubleClickOccured = true;
  20384. clickInfo.doubleClick = true;
  20385. clickInfo.ignore = false;
  20386. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20387. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20388. }
  20389. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20390. cb(clickInfo, _this._currentPickResult);
  20391. }
  20392. else {
  20393. _this._doubleClickOccured = false;
  20394. _this._previousStartingPointerTime = _this._startingPointerTime;
  20395. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20396. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20397. _this._previousButtonPressed = btn;
  20398. if (Scene.ExclusiveDoubleClickMode) {
  20399. if (_this._previousDelayedSimpleClickTimeout) {
  20400. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20401. }
  20402. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20403. cb(clickInfo, _this._previousPickResult);
  20404. }
  20405. else {
  20406. cb(clickInfo, _this._currentPickResult);
  20407. }
  20408. }
  20409. }
  20410. else {
  20411. _this._doubleClickOccured = false;
  20412. _this._previousStartingPointerTime = _this._startingPointerTime;
  20413. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20414. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20415. _this._previousButtonPressed = btn;
  20416. }
  20417. }
  20418. }
  20419. }
  20420. clickInfo.ignore = true;
  20421. cb(clickInfo, _this._currentPickResult);
  20422. };
  20423. this._spritePredicate = function (sprite) {
  20424. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20425. };
  20426. this._onPointerMove = function (evt) {
  20427. _this._updatePointerPosition(evt);
  20428. // PreObservable support
  20429. if (_this.onPrePointerObservable.hasObservers()) {
  20430. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20431. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20432. _this.onPrePointerObservable.notifyObservers(pi, type);
  20433. if (pi.skipOnPointerObservable) {
  20434. return;
  20435. }
  20436. }
  20437. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20438. return;
  20439. }
  20440. if (!_this.pointerMovePredicate) {
  20441. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20442. }
  20443. // Meshes
  20444. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20445. _this._processPointerMove(pickResult, evt);
  20446. };
  20447. this._onPointerDown = function (evt) {
  20448. _this._totalPointersPressed++;
  20449. _this._pickedDownMesh = null;
  20450. _this._meshPickProceed = false;
  20451. _this._updatePointerPosition(evt);
  20452. if (_this.preventDefaultOnPointerDown && canvas) {
  20453. evt.preventDefault();
  20454. canvas.focus();
  20455. }
  20456. // PreObservable support
  20457. if (_this.onPrePointerObservable.hasObservers()) {
  20458. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20459. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20460. _this.onPrePointerObservable.notifyObservers(pi, type);
  20461. if (pi.skipOnPointerObservable) {
  20462. return;
  20463. }
  20464. }
  20465. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20466. return;
  20467. }
  20468. _this._startingPointerPosition.x = _this._pointerX;
  20469. _this._startingPointerPosition.y = _this._pointerY;
  20470. _this._startingPointerTime = new Date().getTime();
  20471. if (!_this.pointerDownPredicate) {
  20472. _this.pointerDownPredicate = function (mesh) {
  20473. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20474. };
  20475. }
  20476. // Meshes
  20477. _this._pickedDownMesh = null;
  20478. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20479. _this._processPointerDown(pickResult, evt);
  20480. // Sprites
  20481. _this._pickedDownSprite = null;
  20482. if (_this.spriteManagers.length > 0) {
  20483. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20484. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20485. if (pickResult.pickedSprite.actionManager) {
  20486. _this._pickedDownSprite = pickResult.pickedSprite;
  20487. switch (evt.button) {
  20488. case 0:
  20489. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20490. break;
  20491. case 1:
  20492. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20493. break;
  20494. case 2:
  20495. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20496. break;
  20497. }
  20498. if (pickResult.pickedSprite.actionManager) {
  20499. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20500. }
  20501. }
  20502. }
  20503. }
  20504. };
  20505. this._onPointerUp = function (evt) {
  20506. if (_this._totalPointersPressed === 0) {
  20507. return; // So we need to test it the pointer down was pressed before.
  20508. }
  20509. _this._totalPointersPressed--;
  20510. _this._pickedUpMesh = null;
  20511. _this._meshPickProceed = false;
  20512. _this._updatePointerPosition(evt);
  20513. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20514. // PreObservable support
  20515. if (_this.onPrePointerObservable.hasObservers()) {
  20516. if (!clickInfo.ignore) {
  20517. if (!clickInfo.hasSwiped) {
  20518. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20519. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20520. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20521. _this.onPrePointerObservable.notifyObservers(pi, type);
  20522. if (pi.skipOnPointerObservable) {
  20523. return;
  20524. }
  20525. }
  20526. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20527. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20528. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20529. _this.onPrePointerObservable.notifyObservers(pi, type);
  20530. if (pi.skipOnPointerObservable) {
  20531. return;
  20532. }
  20533. }
  20534. }
  20535. }
  20536. else {
  20537. var type = BABYLON.PointerEventTypes.POINTERUP;
  20538. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20539. _this.onPrePointerObservable.notifyObservers(pi, type);
  20540. if (pi.skipOnPointerObservable) {
  20541. return;
  20542. }
  20543. }
  20544. }
  20545. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20546. return;
  20547. }
  20548. if (!_this.pointerUpPredicate) {
  20549. _this.pointerUpPredicate = function (mesh) {
  20550. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20551. };
  20552. }
  20553. // Meshes
  20554. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20555. _this._initActionManager(null, clickInfo);
  20556. }
  20557. if (!pickResult) {
  20558. pickResult = _this._currentPickResult;
  20559. }
  20560. _this._processPointerUp(pickResult, evt, clickInfo);
  20561. // Sprites
  20562. if (_this.spriteManagers.length > 0) {
  20563. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20564. if (spritePickResult) {
  20565. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20566. if (spritePickResult.pickedSprite.actionManager) {
  20567. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20568. if (spritePickResult.pickedSprite.actionManager) {
  20569. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20570. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20571. }
  20572. }
  20573. }
  20574. }
  20575. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20576. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20577. }
  20578. }
  20579. }
  20580. _this._previousPickResult = _this._currentPickResult;
  20581. });
  20582. };
  20583. this._onKeyDown = function (evt) {
  20584. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20585. if (_this.onPreKeyboardObservable.hasObservers()) {
  20586. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20587. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20588. if (pi.skipOnPointerObservable) {
  20589. return;
  20590. }
  20591. }
  20592. if (_this.onKeyboardObservable.hasObservers()) {
  20593. var pi = new BABYLON.KeyboardInfo(type, evt);
  20594. _this.onKeyboardObservable.notifyObservers(pi, type);
  20595. }
  20596. if (_this.actionManager) {
  20597. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20598. }
  20599. };
  20600. this._onKeyUp = function (evt) {
  20601. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20602. if (_this.onPreKeyboardObservable.hasObservers()) {
  20603. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20604. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20605. if (pi.skipOnPointerObservable) {
  20606. return;
  20607. }
  20608. }
  20609. if (_this.onKeyboardObservable.hasObservers()) {
  20610. var pi = new BABYLON.KeyboardInfo(type, evt);
  20611. _this.onKeyboardObservable.notifyObservers(pi, type);
  20612. }
  20613. if (_this.actionManager) {
  20614. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20615. }
  20616. };
  20617. var engine = this.getEngine();
  20618. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20619. if (!canvas) {
  20620. return;
  20621. }
  20622. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20623. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20624. });
  20625. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20626. if (!canvas) {
  20627. return;
  20628. }
  20629. canvas.removeEventListener("keydown", _this._onKeyDown);
  20630. canvas.removeEventListener("keyup", _this._onKeyUp);
  20631. });
  20632. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20633. var canvas = this._engine.getRenderingCanvas();
  20634. if (!canvas) {
  20635. return;
  20636. }
  20637. if (attachMove) {
  20638. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20639. // Wheel
  20640. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20641. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20642. }
  20643. if (attachDown) {
  20644. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20645. }
  20646. if (attachUp) {
  20647. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20648. }
  20649. canvas.tabIndex = 1;
  20650. };
  20651. Scene.prototype.detachControl = function () {
  20652. var engine = this.getEngine();
  20653. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20654. var canvas = engine.getRenderingCanvas();
  20655. if (!canvas) {
  20656. return;
  20657. }
  20658. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20659. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20660. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20661. if (this._onCanvasBlurObserver) {
  20662. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20663. }
  20664. if (this._onCanvasFocusObserver) {
  20665. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20666. }
  20667. // Wheel
  20668. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20669. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20670. // Keyboard
  20671. canvas.removeEventListener("keydown", this._onKeyDown);
  20672. canvas.removeEventListener("keyup", this._onKeyUp);
  20673. // Observables
  20674. this.onKeyboardObservable.clear();
  20675. this.onPreKeyboardObservable.clear();
  20676. this.onPointerObservable.clear();
  20677. this.onPrePointerObservable.clear();
  20678. };
  20679. // Ready
  20680. Scene.prototype.isReady = function () {
  20681. if (this._isDisposed) {
  20682. return false;
  20683. }
  20684. if (this._pendingData.length > 0) {
  20685. return false;
  20686. }
  20687. var index;
  20688. // Geometries
  20689. for (index = 0; index < this._geometries.length; index++) {
  20690. var geometry = this._geometries[index];
  20691. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20692. return false;
  20693. }
  20694. }
  20695. // Meshes
  20696. for (index = 0; index < this.meshes.length; index++) {
  20697. var mesh = this.meshes[index];
  20698. if (!mesh.isEnabled()) {
  20699. continue;
  20700. }
  20701. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20702. continue;
  20703. }
  20704. if (!mesh.isReady()) {
  20705. return false;
  20706. }
  20707. var mat = mesh.material;
  20708. if (mat) {
  20709. if (!mat.isReady(mesh)) {
  20710. return false;
  20711. }
  20712. }
  20713. }
  20714. return true;
  20715. };
  20716. Scene.prototype.resetCachedMaterial = function () {
  20717. this._cachedMaterial = null;
  20718. this._cachedEffect = null;
  20719. this._cachedVisibility = null;
  20720. };
  20721. Scene.prototype.registerBeforeRender = function (func) {
  20722. this.onBeforeRenderObservable.add(func);
  20723. };
  20724. Scene.prototype.unregisterBeforeRender = function (func) {
  20725. this.onBeforeRenderObservable.removeCallback(func);
  20726. };
  20727. Scene.prototype.registerAfterRender = function (func) {
  20728. this.onAfterRenderObservable.add(func);
  20729. };
  20730. Scene.prototype.unregisterAfterRender = function (func) {
  20731. this.onAfterRenderObservable.removeCallback(func);
  20732. };
  20733. Scene.prototype._executeOnceBeforeRender = function (func) {
  20734. var _this = this;
  20735. var execFunc = function () {
  20736. func();
  20737. setTimeout(function () {
  20738. _this.unregisterBeforeRender(execFunc);
  20739. });
  20740. };
  20741. this.registerBeforeRender(execFunc);
  20742. };
  20743. /**
  20744. * The provided function will run before render once and will be disposed afterwards.
  20745. * A timeout delay can be provided so that the function will be executed in N ms.
  20746. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20747. * @param func The function to be executed.
  20748. * @param timeout optional delay in ms
  20749. */
  20750. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20751. var _this = this;
  20752. if (timeout !== undefined) {
  20753. setTimeout(function () {
  20754. _this._executeOnceBeforeRender(func);
  20755. }, timeout);
  20756. }
  20757. else {
  20758. this._executeOnceBeforeRender(func);
  20759. }
  20760. };
  20761. Scene.prototype._addPendingData = function (data) {
  20762. this._pendingData.push(data);
  20763. };
  20764. Scene.prototype._removePendingData = function (data) {
  20765. var wasLoading = this.isLoading;
  20766. var index = this._pendingData.indexOf(data);
  20767. if (index !== -1) {
  20768. this._pendingData.splice(index, 1);
  20769. }
  20770. if (wasLoading && !this.isLoading) {
  20771. this.onDataLoadedObservable.notifyObservers(this);
  20772. }
  20773. };
  20774. Scene.prototype.getWaitingItemsCount = function () {
  20775. return this._pendingData.length;
  20776. };
  20777. Object.defineProperty(Scene.prototype, "isLoading", {
  20778. get: function () {
  20779. return this._pendingData.length > 0;
  20780. },
  20781. enumerable: true,
  20782. configurable: true
  20783. });
  20784. /**
  20785. * Registers a function to be executed when the scene is ready.
  20786. * @param {Function} func - the function to be executed.
  20787. */
  20788. Scene.prototype.executeWhenReady = function (func) {
  20789. var _this = this;
  20790. this.onReadyObservable.add(func);
  20791. if (this._executeWhenReadyTimeoutId !== -1) {
  20792. return;
  20793. }
  20794. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20795. _this._checkIsReady();
  20796. }, 150);
  20797. };
  20798. Scene.prototype._checkIsReady = function () {
  20799. var _this = this;
  20800. if (this.isReady()) {
  20801. this.onReadyObservable.notifyObservers(this);
  20802. this.onReadyObservable.clear();
  20803. this._executeWhenReadyTimeoutId = -1;
  20804. return;
  20805. }
  20806. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20807. _this._checkIsReady();
  20808. }, 150);
  20809. };
  20810. // Animations
  20811. /**
  20812. * Will start the animation sequence of a given target
  20813. * @param target - the target
  20814. * @param {number} from - from which frame should animation start
  20815. * @param {number} to - till which frame should animation run.
  20816. * @param {boolean} [loop] - should the animation loop
  20817. * @param {number} [speedRatio] - the speed in which to run the animation
  20818. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20819. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20820. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20821. * See BABYLON.Animatable
  20822. */
  20823. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20824. if (speedRatio === void 0) { speedRatio = 1.0; }
  20825. if (from > to && speedRatio > 0) {
  20826. speedRatio *= -1;
  20827. }
  20828. this.stopAnimation(target);
  20829. if (!animatable) {
  20830. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20831. }
  20832. // Local animations
  20833. if (target.animations) {
  20834. animatable.appendAnimations(target, target.animations);
  20835. }
  20836. // Children animations
  20837. if (target.getAnimatables) {
  20838. var animatables = target.getAnimatables();
  20839. for (var index = 0; index < animatables.length; index++) {
  20840. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20841. }
  20842. }
  20843. animatable.reset();
  20844. return animatable;
  20845. };
  20846. /**
  20847. * Begin a new animation on a given node
  20848. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20849. * @param {BABYLON.Animation[]} defines the list of animations to start
  20850. * @param {number} from defines the initial value
  20851. * @param {number} to defines the final value
  20852. * @param {boolean} loop defines if you want animation to loop (off by default)
  20853. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20854. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20855. * @returns the list of created animatables
  20856. */
  20857. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20858. if (speedRatio === undefined) {
  20859. speedRatio = 1.0;
  20860. }
  20861. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20862. return animatable;
  20863. };
  20864. /**
  20865. * Begin a new animation on a given node and its hierarchy
  20866. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20867. * @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.
  20868. * @param {BABYLON.Animation[]} defines the list of animations to start
  20869. * @param {number} from defines the initial value
  20870. * @param {number} to defines the final value
  20871. * @param {boolean} loop defines if you want animation to loop (off by default)
  20872. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20873. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20874. * @returns the list of animatables created for all nodes
  20875. */
  20876. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20877. var children = target.getDescendants(directDescendantsOnly);
  20878. var result = [];
  20879. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20880. var child = children_1[_i];
  20881. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20882. }
  20883. return result;
  20884. };
  20885. Scene.prototype.getAnimatableByTarget = function (target) {
  20886. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20887. if (this._activeAnimatables[index].target === target) {
  20888. return this._activeAnimatables[index];
  20889. }
  20890. }
  20891. return null;
  20892. };
  20893. Object.defineProperty(Scene.prototype, "animatables", {
  20894. get: function () {
  20895. return this._activeAnimatables;
  20896. },
  20897. enumerable: true,
  20898. configurable: true
  20899. });
  20900. /**
  20901. * Will stop the animation of the given target
  20902. * @param target - the target
  20903. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20904. * @see beginAnimation
  20905. */
  20906. Scene.prototype.stopAnimation = function (target, animationName) {
  20907. var animatable = this.getAnimatableByTarget(target);
  20908. if (animatable) {
  20909. animatable.stop(animationName);
  20910. }
  20911. };
  20912. /**
  20913. * Stops and removes all animations that have been applied to the scene
  20914. */
  20915. Scene.prototype.stopAllAnimations = function () {
  20916. if (this._activeAnimatables) {
  20917. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20918. this._activeAnimatables[i].stop();
  20919. }
  20920. this._activeAnimatables = [];
  20921. }
  20922. };
  20923. Scene.prototype._animate = function () {
  20924. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20925. return;
  20926. }
  20927. // Getting time
  20928. var now = BABYLON.Tools.Now;
  20929. if (!this._animationTimeLast) {
  20930. if (this._pendingData.length > 0) {
  20931. return;
  20932. }
  20933. this._animationTimeLast = now;
  20934. }
  20935. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20936. this._animationTime += deltaTime;
  20937. this._animationTimeLast = now;
  20938. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20939. this._activeAnimatables[index]._animate(this._animationTime);
  20940. }
  20941. };
  20942. // Matrix
  20943. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20944. this._useAlternateCameraConfiguration = active;
  20945. };
  20946. Scene.prototype.getViewMatrix = function () {
  20947. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20948. };
  20949. Scene.prototype.getProjectionMatrix = function () {
  20950. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20951. };
  20952. Scene.prototype.getTransformMatrix = function () {
  20953. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20954. };
  20955. Scene.prototype.setTransformMatrix = function (view, projection) {
  20956. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20957. return;
  20958. }
  20959. this._viewUpdateFlag = view.updateFlag;
  20960. this._projectionUpdateFlag = projection.updateFlag;
  20961. this._viewMatrix = view;
  20962. this._projectionMatrix = projection;
  20963. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20964. // Update frustum
  20965. if (!this._frustumPlanes) {
  20966. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20967. }
  20968. else {
  20969. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20970. }
  20971. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20972. var otherCamera = this.activeCamera._alternateCamera;
  20973. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20974. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20975. }
  20976. if (this._sceneUbo.useUbo) {
  20977. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20978. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20979. this._sceneUbo.update();
  20980. }
  20981. };
  20982. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20983. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20984. return;
  20985. }
  20986. this._alternateViewUpdateFlag = view.updateFlag;
  20987. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20988. this._alternateViewMatrix = view;
  20989. this._alternateProjectionMatrix = projection;
  20990. if (!this._alternateTransformMatrix) {
  20991. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20992. }
  20993. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20994. if (!this._alternateSceneUbo) {
  20995. this._createAlternateUbo();
  20996. }
  20997. if (this._alternateSceneUbo.useUbo) {
  20998. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  20999. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21000. this._alternateSceneUbo.update();
  21001. }
  21002. };
  21003. Scene.prototype.getSceneUniformBuffer = function () {
  21004. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21005. };
  21006. // Methods
  21007. Scene.prototype.getUniqueId = function () {
  21008. var result = Scene._uniqueIdCounter;
  21009. Scene._uniqueIdCounter++;
  21010. return result;
  21011. };
  21012. Scene.prototype.addMesh = function (newMesh) {
  21013. this.meshes.push(newMesh);
  21014. //notify the collision coordinator
  21015. if (this.collisionCoordinator) {
  21016. this.collisionCoordinator.onMeshAdded(newMesh);
  21017. }
  21018. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21019. };
  21020. Scene.prototype.removeMesh = function (toRemove) {
  21021. var index = this.meshes.indexOf(toRemove);
  21022. if (index !== -1) {
  21023. // Remove from the scene if mesh found
  21024. this.meshes.splice(index, 1);
  21025. }
  21026. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21027. return index;
  21028. };
  21029. Scene.prototype.addTransformNode = function (newTransformNode) {
  21030. this.transformNodes.push(newTransformNode);
  21031. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21032. };
  21033. Scene.prototype.removeTransformNode = function (toRemove) {
  21034. var index = this.transformNodes.indexOf(toRemove);
  21035. if (index !== -1) {
  21036. // Remove from the scene if found
  21037. this.transformNodes.splice(index, 1);
  21038. }
  21039. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21040. return index;
  21041. };
  21042. Scene.prototype.removeSkeleton = function (toRemove) {
  21043. var index = this.skeletons.indexOf(toRemove);
  21044. if (index !== -1) {
  21045. // Remove from the scene if found
  21046. this.skeletons.splice(index, 1);
  21047. }
  21048. return index;
  21049. };
  21050. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21051. var index = this.morphTargetManagers.indexOf(toRemove);
  21052. if (index !== -1) {
  21053. // Remove from the scene if found
  21054. this.morphTargetManagers.splice(index, 1);
  21055. }
  21056. return index;
  21057. };
  21058. Scene.prototype.removeLight = function (toRemove) {
  21059. var index = this.lights.indexOf(toRemove);
  21060. if (index !== -1) {
  21061. // Remove from meshes
  21062. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21063. var mesh = _a[_i];
  21064. mesh._removeLightSource(toRemove);
  21065. }
  21066. // Remove from the scene if mesh found
  21067. this.lights.splice(index, 1);
  21068. this.sortLightsByPriority();
  21069. }
  21070. this.onLightRemovedObservable.notifyObservers(toRemove);
  21071. return index;
  21072. };
  21073. Scene.prototype.removeCamera = function (toRemove) {
  21074. var index = this.cameras.indexOf(toRemove);
  21075. if (index !== -1) {
  21076. // Remove from the scene if mesh found
  21077. this.cameras.splice(index, 1);
  21078. }
  21079. // Remove from activeCameras
  21080. var index2 = this.activeCameras.indexOf(toRemove);
  21081. if (index2 !== -1) {
  21082. // Remove from the scene if mesh found
  21083. this.activeCameras.splice(index2, 1);
  21084. }
  21085. // Reset the activeCamera
  21086. if (this.activeCamera === toRemove) {
  21087. if (this.cameras.length > 0) {
  21088. this.activeCamera = this.cameras[0];
  21089. }
  21090. else {
  21091. this.activeCamera = null;
  21092. }
  21093. }
  21094. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21095. return index;
  21096. };
  21097. Scene.prototype.addLight = function (newLight) {
  21098. this.lights.push(newLight);
  21099. this.sortLightsByPriority();
  21100. // Add light to all meshes (To support if the light is removed and then readded)
  21101. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21102. var mesh = _a[_i];
  21103. if (mesh._lightSources.indexOf(newLight) === -1) {
  21104. mesh._lightSources.push(newLight);
  21105. mesh._resyncLightSources();
  21106. }
  21107. }
  21108. this.onNewLightAddedObservable.notifyObservers(newLight);
  21109. };
  21110. Scene.prototype.sortLightsByPriority = function () {
  21111. if (this.requireLightSorting) {
  21112. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21113. }
  21114. };
  21115. Scene.prototype.addCamera = function (newCamera) {
  21116. this.cameras.push(newCamera);
  21117. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21118. };
  21119. /**
  21120. * Switch active camera
  21121. * @param {Camera} newCamera - new active camera
  21122. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21123. */
  21124. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21125. if (attachControl === void 0) { attachControl = true; }
  21126. var canvas = this._engine.getRenderingCanvas();
  21127. if (!canvas) {
  21128. return;
  21129. }
  21130. if (this.activeCamera) {
  21131. this.activeCamera.detachControl(canvas);
  21132. }
  21133. this.activeCamera = newCamera;
  21134. if (attachControl) {
  21135. newCamera.attachControl(canvas);
  21136. }
  21137. };
  21138. /**
  21139. * sets the active camera of the scene using its ID
  21140. * @param {string} id - the camera's ID
  21141. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21142. * @see activeCamera
  21143. */
  21144. Scene.prototype.setActiveCameraByID = function (id) {
  21145. var camera = this.getCameraByID(id);
  21146. if (camera) {
  21147. this.activeCamera = camera;
  21148. return camera;
  21149. }
  21150. return null;
  21151. };
  21152. /**
  21153. * sets the active camera of the scene using its name
  21154. * @param {string} name - the camera's name
  21155. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21156. * @see activeCamera
  21157. */
  21158. Scene.prototype.setActiveCameraByName = function (name) {
  21159. var camera = this.getCameraByName(name);
  21160. if (camera) {
  21161. this.activeCamera = camera;
  21162. return camera;
  21163. }
  21164. return null;
  21165. };
  21166. /**
  21167. * get an animation group using its name
  21168. * @param {string} the material's name
  21169. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21170. */
  21171. Scene.prototype.getAnimationGroupByName = function (name) {
  21172. for (var index = 0; index < this.animationGroups.length; index++) {
  21173. if (this.animationGroups[index].name === name) {
  21174. return this.animationGroups[index];
  21175. }
  21176. }
  21177. return null;
  21178. };
  21179. /**
  21180. * get a material using its id
  21181. * @param {string} the material's ID
  21182. * @return {BABYLON.Material|null} the material or null if none found.
  21183. */
  21184. Scene.prototype.getMaterialByID = function (id) {
  21185. for (var index = 0; index < this.materials.length; index++) {
  21186. if (this.materials[index].id === id) {
  21187. return this.materials[index];
  21188. }
  21189. }
  21190. return null;
  21191. };
  21192. /**
  21193. * get a material using its name
  21194. * @param {string} the material's name
  21195. * @return {BABYLON.Material|null} the material or null if none found.
  21196. */
  21197. Scene.prototype.getMaterialByName = function (name) {
  21198. for (var index = 0; index < this.materials.length; index++) {
  21199. if (this.materials[index].name === name) {
  21200. return this.materials[index];
  21201. }
  21202. }
  21203. return null;
  21204. };
  21205. Scene.prototype.getLensFlareSystemByName = function (name) {
  21206. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21207. if (this.lensFlareSystems[index].name === name) {
  21208. return this.lensFlareSystems[index];
  21209. }
  21210. }
  21211. return null;
  21212. };
  21213. Scene.prototype.getLensFlareSystemByID = function (id) {
  21214. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21215. if (this.lensFlareSystems[index].id === id) {
  21216. return this.lensFlareSystems[index];
  21217. }
  21218. }
  21219. return null;
  21220. };
  21221. Scene.prototype.getCameraByID = function (id) {
  21222. for (var index = 0; index < this.cameras.length; index++) {
  21223. if (this.cameras[index].id === id) {
  21224. return this.cameras[index];
  21225. }
  21226. }
  21227. return null;
  21228. };
  21229. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21230. for (var index = 0; index < this.cameras.length; index++) {
  21231. if (this.cameras[index].uniqueId === uniqueId) {
  21232. return this.cameras[index];
  21233. }
  21234. }
  21235. return null;
  21236. };
  21237. /**
  21238. * get a camera using its name
  21239. * @param {string} the camera's name
  21240. * @return {BABYLON.Camera|null} the camera or null if none found.
  21241. */
  21242. Scene.prototype.getCameraByName = function (name) {
  21243. for (var index = 0; index < this.cameras.length; index++) {
  21244. if (this.cameras[index].name === name) {
  21245. return this.cameras[index];
  21246. }
  21247. }
  21248. return null;
  21249. };
  21250. /**
  21251. * get a bone using its id
  21252. * @param {string} the bone's id
  21253. * @return {BABYLON.Bone|null} the bone or null if not found
  21254. */
  21255. Scene.prototype.getBoneByID = function (id) {
  21256. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21257. var skeleton = this.skeletons[skeletonIndex];
  21258. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21259. if (skeleton.bones[boneIndex].id === id) {
  21260. return skeleton.bones[boneIndex];
  21261. }
  21262. }
  21263. }
  21264. return null;
  21265. };
  21266. /**
  21267. * get a bone using its id
  21268. * @param {string} the bone's name
  21269. * @return {BABYLON.Bone|null} the bone or null if not found
  21270. */
  21271. Scene.prototype.getBoneByName = function (name) {
  21272. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21273. var skeleton = this.skeletons[skeletonIndex];
  21274. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21275. if (skeleton.bones[boneIndex].name === name) {
  21276. return skeleton.bones[boneIndex];
  21277. }
  21278. }
  21279. }
  21280. return null;
  21281. };
  21282. /**
  21283. * get a light node using its name
  21284. * @param {string} the light's name
  21285. * @return {BABYLON.Light|null} the light or null if none found.
  21286. */
  21287. Scene.prototype.getLightByName = function (name) {
  21288. for (var index = 0; index < this.lights.length; index++) {
  21289. if (this.lights[index].name === name) {
  21290. return this.lights[index];
  21291. }
  21292. }
  21293. return null;
  21294. };
  21295. /**
  21296. * get a light node using its ID
  21297. * @param {string} the light's id
  21298. * @return {BABYLON.Light|null} the light or null if none found.
  21299. */
  21300. Scene.prototype.getLightByID = function (id) {
  21301. for (var index = 0; index < this.lights.length; index++) {
  21302. if (this.lights[index].id === id) {
  21303. return this.lights[index];
  21304. }
  21305. }
  21306. return null;
  21307. };
  21308. /**
  21309. * get a light node using its scene-generated unique ID
  21310. * @param {number} the light's unique id
  21311. * @return {BABYLON.Light|null} the light or null if none found.
  21312. */
  21313. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21314. for (var index = 0; index < this.lights.length; index++) {
  21315. if (this.lights[index].uniqueId === uniqueId) {
  21316. return this.lights[index];
  21317. }
  21318. }
  21319. return null;
  21320. };
  21321. /**
  21322. * get a particle system by id
  21323. * @param id {number} the particle system id
  21324. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21325. */
  21326. Scene.prototype.getParticleSystemByID = function (id) {
  21327. for (var index = 0; index < this.particleSystems.length; index++) {
  21328. if (this.particleSystems[index].id === id) {
  21329. return this.particleSystems[index];
  21330. }
  21331. }
  21332. return null;
  21333. };
  21334. /**
  21335. * get a geometry using its ID
  21336. * @param {string} the geometry's id
  21337. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21338. */
  21339. Scene.prototype.getGeometryByID = function (id) {
  21340. for (var index = 0; index < this._geometries.length; index++) {
  21341. if (this._geometries[index].id === id) {
  21342. return this._geometries[index];
  21343. }
  21344. }
  21345. return null;
  21346. };
  21347. /**
  21348. * add a new geometry to this scene.
  21349. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21350. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21351. * @return {boolean} was the geometry added or not
  21352. */
  21353. Scene.prototype.pushGeometry = function (geometry, force) {
  21354. if (!force && this.getGeometryByID(geometry.id)) {
  21355. return false;
  21356. }
  21357. this._geometries.push(geometry);
  21358. //notify the collision coordinator
  21359. if (this.collisionCoordinator) {
  21360. this.collisionCoordinator.onGeometryAdded(geometry);
  21361. }
  21362. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21363. return true;
  21364. };
  21365. /**
  21366. * Removes an existing geometry
  21367. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21368. * @return {boolean} was the geometry removed or not
  21369. */
  21370. Scene.prototype.removeGeometry = function (geometry) {
  21371. var index = this._geometries.indexOf(geometry);
  21372. if (index > -1) {
  21373. this._geometries.splice(index, 1);
  21374. //notify the collision coordinator
  21375. if (this.collisionCoordinator) {
  21376. this.collisionCoordinator.onGeometryDeleted(geometry);
  21377. }
  21378. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21379. return true;
  21380. }
  21381. return false;
  21382. };
  21383. Scene.prototype.getGeometries = function () {
  21384. return this._geometries;
  21385. };
  21386. /**
  21387. * Get the first added mesh found of a given ID
  21388. * @param {string} id - the id to search for
  21389. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21390. */
  21391. Scene.prototype.getMeshByID = function (id) {
  21392. for (var index = 0; index < this.meshes.length; index++) {
  21393. if (this.meshes[index].id === id) {
  21394. return this.meshes[index];
  21395. }
  21396. }
  21397. return null;
  21398. };
  21399. Scene.prototype.getMeshesByID = function (id) {
  21400. return this.meshes.filter(function (m) {
  21401. return m.id === id;
  21402. });
  21403. };
  21404. /**
  21405. * Get the first added transform node found of a given ID
  21406. * @param {string} id - the id to search for
  21407. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21408. */
  21409. Scene.prototype.getTransformNodeByID = function (id) {
  21410. for (var index = 0; index < this.transformNodes.length; index++) {
  21411. if (this.transformNodes[index].id === id) {
  21412. return this.transformNodes[index];
  21413. }
  21414. }
  21415. return null;
  21416. };
  21417. Scene.prototype.getTransformNodesByID = function (id) {
  21418. return this.transformNodes.filter(function (m) {
  21419. return m.id === id;
  21420. });
  21421. };
  21422. /**
  21423. * Get a mesh with its auto-generated unique id
  21424. * @param {number} uniqueId - the unique id to search for
  21425. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21426. */
  21427. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21428. for (var index = 0; index < this.meshes.length; index++) {
  21429. if (this.meshes[index].uniqueId === uniqueId) {
  21430. return this.meshes[index];
  21431. }
  21432. }
  21433. return null;
  21434. };
  21435. /**
  21436. * Get a the last added mesh found of a given ID
  21437. * @param {string} id - the id to search for
  21438. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21439. */
  21440. Scene.prototype.getLastMeshByID = function (id) {
  21441. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21442. if (this.meshes[index].id === id) {
  21443. return this.meshes[index];
  21444. }
  21445. }
  21446. return null;
  21447. };
  21448. /**
  21449. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21450. * @param {string} id - the id to search for
  21451. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21452. */
  21453. Scene.prototype.getLastEntryByID = function (id) {
  21454. var index;
  21455. for (index = this.meshes.length - 1; index >= 0; index--) {
  21456. if (this.meshes[index].id === id) {
  21457. return this.meshes[index];
  21458. }
  21459. }
  21460. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21461. if (this.transformNodes[index].id === id) {
  21462. return this.transformNodes[index];
  21463. }
  21464. }
  21465. for (index = this.cameras.length - 1; index >= 0; index--) {
  21466. if (this.cameras[index].id === id) {
  21467. return this.cameras[index];
  21468. }
  21469. }
  21470. for (index = this.lights.length - 1; index >= 0; index--) {
  21471. if (this.lights[index].id === id) {
  21472. return this.lights[index];
  21473. }
  21474. }
  21475. return null;
  21476. };
  21477. Scene.prototype.getNodeByID = function (id) {
  21478. var mesh = this.getMeshByID(id);
  21479. if (mesh) {
  21480. return mesh;
  21481. }
  21482. var light = this.getLightByID(id);
  21483. if (light) {
  21484. return light;
  21485. }
  21486. var camera = this.getCameraByID(id);
  21487. if (camera) {
  21488. return camera;
  21489. }
  21490. var bone = this.getBoneByID(id);
  21491. return bone;
  21492. };
  21493. Scene.prototype.getNodeByName = function (name) {
  21494. var mesh = this.getMeshByName(name);
  21495. if (mesh) {
  21496. return mesh;
  21497. }
  21498. var light = this.getLightByName(name);
  21499. if (light) {
  21500. return light;
  21501. }
  21502. var camera = this.getCameraByName(name);
  21503. if (camera) {
  21504. return camera;
  21505. }
  21506. var bone = this.getBoneByName(name);
  21507. return bone;
  21508. };
  21509. Scene.prototype.getMeshByName = function (name) {
  21510. for (var index = 0; index < this.meshes.length; index++) {
  21511. if (this.meshes[index].name === name) {
  21512. return this.meshes[index];
  21513. }
  21514. }
  21515. return null;
  21516. };
  21517. Scene.prototype.getTransformNodeByName = function (name) {
  21518. for (var index = 0; index < this.transformNodes.length; index++) {
  21519. if (this.transformNodes[index].name === name) {
  21520. return this.transformNodes[index];
  21521. }
  21522. }
  21523. return null;
  21524. };
  21525. Scene.prototype.getSoundByName = function (name) {
  21526. var index;
  21527. if (BABYLON.AudioEngine) {
  21528. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21529. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21530. return this.mainSoundTrack.soundCollection[index];
  21531. }
  21532. }
  21533. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21534. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21535. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21536. return this.soundTracks[sdIndex].soundCollection[index];
  21537. }
  21538. }
  21539. }
  21540. }
  21541. return null;
  21542. };
  21543. Scene.prototype.getLastSkeletonByID = function (id) {
  21544. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21545. if (this.skeletons[index].id === id) {
  21546. return this.skeletons[index];
  21547. }
  21548. }
  21549. return null;
  21550. };
  21551. Scene.prototype.getSkeletonById = function (id) {
  21552. for (var index = 0; index < this.skeletons.length; index++) {
  21553. if (this.skeletons[index].id === id) {
  21554. return this.skeletons[index];
  21555. }
  21556. }
  21557. return null;
  21558. };
  21559. Scene.prototype.getSkeletonByName = function (name) {
  21560. for (var index = 0; index < this.skeletons.length; index++) {
  21561. if (this.skeletons[index].name === name) {
  21562. return this.skeletons[index];
  21563. }
  21564. }
  21565. return null;
  21566. };
  21567. Scene.prototype.getMorphTargetManagerById = function (id) {
  21568. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21569. if (this.morphTargetManagers[index].uniqueId === id) {
  21570. return this.morphTargetManagers[index];
  21571. }
  21572. }
  21573. return null;
  21574. };
  21575. Scene.prototype.isActiveMesh = function (mesh) {
  21576. return (this._activeMeshes.indexOf(mesh) !== -1);
  21577. };
  21578. /**
  21579. * Return a the first highlight layer of the scene with a given name.
  21580. * @param name The name of the highlight layer to look for.
  21581. * @return The highlight layer if found otherwise null.
  21582. */
  21583. Scene.prototype.getHighlightLayerByName = function (name) {
  21584. for (var index = 0; index < this.highlightLayers.length; index++) {
  21585. if (this.highlightLayers[index].name === name) {
  21586. return this.highlightLayers[index];
  21587. }
  21588. }
  21589. return null;
  21590. };
  21591. Object.defineProperty(Scene.prototype, "uid", {
  21592. /**
  21593. * Return a unique id as a string which can serve as an identifier for the scene
  21594. */
  21595. get: function () {
  21596. if (!this._uid) {
  21597. this._uid = BABYLON.Tools.RandomId();
  21598. }
  21599. return this._uid;
  21600. },
  21601. enumerable: true,
  21602. configurable: true
  21603. });
  21604. /**
  21605. * Add an externaly attached data from its key.
  21606. * This method call will fail and return false, if such key already exists.
  21607. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21608. * @param key the unique key that identifies the data
  21609. * @param data the data object to associate to the key for this Engine instance
  21610. * @return true if no such key were already present and the data was added successfully, false otherwise
  21611. */
  21612. Scene.prototype.addExternalData = function (key, data) {
  21613. if (!this._externalData) {
  21614. this._externalData = new BABYLON.StringDictionary();
  21615. }
  21616. return this._externalData.add(key, data);
  21617. };
  21618. /**
  21619. * Get an externaly attached data from its key
  21620. * @param key the unique key that identifies the data
  21621. * @return the associated data, if present (can be null), or undefined if not present
  21622. */
  21623. Scene.prototype.getExternalData = function (key) {
  21624. if (!this._externalData) {
  21625. return null;
  21626. }
  21627. return this._externalData.get(key);
  21628. };
  21629. /**
  21630. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21631. * @param key the unique key that identifies the data
  21632. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21633. * @return the associated data, can be null if the factory returned null.
  21634. */
  21635. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21636. if (!this._externalData) {
  21637. this._externalData = new BABYLON.StringDictionary();
  21638. }
  21639. return this._externalData.getOrAddWithFactory(key, factory);
  21640. };
  21641. /**
  21642. * Remove an externaly attached data from the Engine instance
  21643. * @param key the unique key that identifies the data
  21644. * @return true if the data was successfully removed, false if it doesn't exist
  21645. */
  21646. Scene.prototype.removeExternalData = function (key) {
  21647. return this._externalData.remove(key);
  21648. };
  21649. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21650. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21651. if (mesh.showSubMeshesBoundingBox) {
  21652. var boundingInfo = subMesh.getBoundingInfo();
  21653. if (boundingInfo !== null && boundingInfo !== undefined) {
  21654. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21655. }
  21656. }
  21657. var material = subMesh.getMaterial();
  21658. if (material !== null && material !== undefined) {
  21659. // Render targets
  21660. if (material.getRenderTargetTextures !== undefined) {
  21661. if (this._processedMaterials.indexOf(material) === -1) {
  21662. this._processedMaterials.push(material);
  21663. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21664. }
  21665. }
  21666. // Dispatch
  21667. this._activeIndices.addCount(subMesh.indexCount, false);
  21668. this._renderingManager.dispatch(subMesh, mesh, material);
  21669. }
  21670. }
  21671. };
  21672. Scene.prototype._isInIntermediateRendering = function () {
  21673. return this._intermediateRendering;
  21674. };
  21675. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21676. this._activeMeshCandidateProvider = provider;
  21677. };
  21678. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21679. return this._activeMeshCandidateProvider;
  21680. };
  21681. /**
  21682. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21683. */
  21684. Scene.prototype.freezeActiveMeshes = function () {
  21685. this._evaluateActiveMeshes();
  21686. this._activeMeshesFrozen = true;
  21687. return this;
  21688. };
  21689. /**
  21690. * Use this function to restart evaluating active meshes on every frame
  21691. */
  21692. Scene.prototype.unfreezeActiveMeshes = function () {
  21693. this._activeMeshesFrozen = false;
  21694. return this;
  21695. };
  21696. Scene.prototype._evaluateActiveMeshes = function () {
  21697. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21698. return;
  21699. }
  21700. if (!this.activeCamera) {
  21701. return;
  21702. }
  21703. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21704. this.activeCamera._activeMeshes.reset();
  21705. this._activeMeshes.reset();
  21706. this._renderingManager.reset();
  21707. this._processedMaterials.reset();
  21708. this._activeParticleSystems.reset();
  21709. this._activeSkeletons.reset();
  21710. this._softwareSkinnedMeshes.reset();
  21711. if (this._boundingBoxRenderer) {
  21712. this._boundingBoxRenderer.reset();
  21713. }
  21714. // Meshes
  21715. var meshes;
  21716. var len;
  21717. var checkIsEnabled = true;
  21718. // Determine mesh candidates
  21719. if (this._activeMeshCandidateProvider !== undefined) {
  21720. // Use _activeMeshCandidateProvider
  21721. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21722. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21723. if (meshes !== undefined) {
  21724. len = meshes.length;
  21725. }
  21726. else {
  21727. len = 0;
  21728. }
  21729. }
  21730. else if (this._selectionOctree !== undefined) {
  21731. // Octree
  21732. var selection = this._selectionOctree.select(this._frustumPlanes);
  21733. meshes = selection.data;
  21734. len = selection.length;
  21735. }
  21736. else {
  21737. // Full scene traversal
  21738. len = this.meshes.length;
  21739. meshes = this.meshes;
  21740. }
  21741. // Check each mesh
  21742. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21743. mesh = meshes[meshIndex];
  21744. if (mesh.isBlocked) {
  21745. continue;
  21746. }
  21747. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21748. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21749. continue;
  21750. }
  21751. mesh.computeWorldMatrix();
  21752. // Intersections
  21753. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21754. this._meshesForIntersections.pushNoDuplicate(mesh);
  21755. }
  21756. // Switch to current LOD
  21757. meshLOD = mesh.getLOD(this.activeCamera);
  21758. if (meshLOD === undefined || meshLOD === null) {
  21759. continue;
  21760. }
  21761. mesh._preActivate();
  21762. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21763. this._activeMeshes.push(mesh);
  21764. this.activeCamera._activeMeshes.push(mesh);
  21765. mesh._activate(this._renderId);
  21766. if (meshLOD !== mesh) {
  21767. meshLOD._activate(this._renderId);
  21768. }
  21769. this._activeMesh(mesh, meshLOD);
  21770. }
  21771. }
  21772. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21773. // Particle systems
  21774. if (this.particlesEnabled) {
  21775. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21776. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21777. var particleSystem = this.particleSystems[particleIndex];
  21778. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21779. continue;
  21780. }
  21781. var emitter = particleSystem.emitter;
  21782. if (!emitter.position || emitter.isEnabled()) {
  21783. this._activeParticleSystems.push(particleSystem);
  21784. particleSystem.animate();
  21785. this._renderingManager.dispatchParticles(particleSystem);
  21786. }
  21787. }
  21788. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21789. }
  21790. };
  21791. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21792. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21793. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21794. mesh.skeleton.prepare();
  21795. }
  21796. if (!mesh.computeBonesUsingShaders) {
  21797. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21798. }
  21799. }
  21800. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21801. var boundingInfo = sourceMesh.getBoundingInfo();
  21802. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21803. }
  21804. if (mesh !== undefined && mesh !== null
  21805. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21806. // Submeshes Octrees
  21807. var len;
  21808. var subMeshes;
  21809. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21810. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21811. len = intersections.length;
  21812. subMeshes = intersections.data;
  21813. }
  21814. else {
  21815. subMeshes = mesh.subMeshes;
  21816. len = subMeshes.length;
  21817. }
  21818. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21819. subMesh = subMeshes[subIndex];
  21820. this._evaluateSubMesh(subMesh, mesh);
  21821. }
  21822. }
  21823. };
  21824. Scene.prototype.updateTransformMatrix = function (force) {
  21825. if (!this.activeCamera) {
  21826. return;
  21827. }
  21828. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21829. };
  21830. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21831. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21832. };
  21833. Scene.prototype._renderForCamera = function (camera) {
  21834. if (camera && camera._skipRendering) {
  21835. return;
  21836. }
  21837. var engine = this._engine;
  21838. this.activeCamera = camera;
  21839. if (!this.activeCamera)
  21840. throw new Error("Active camera not set");
  21841. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21842. // Viewport
  21843. engine.setViewport(this.activeCamera.viewport);
  21844. // Camera
  21845. this.resetCachedMaterial();
  21846. this._renderId++;
  21847. this.activeCamera.update();
  21848. this.updateTransformMatrix();
  21849. if (camera._alternateCamera) {
  21850. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21851. this._alternateRendering = true;
  21852. }
  21853. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21854. // Meshes
  21855. this._evaluateActiveMeshes();
  21856. // Software skinning
  21857. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21858. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21859. mesh.applySkeleton(mesh.skeleton);
  21860. }
  21861. // Render targets
  21862. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21863. var needsRestoreFrameBuffer = false;
  21864. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21865. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21866. }
  21867. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21868. this._intermediateRendering = true;
  21869. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21870. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21871. var renderTarget = this._renderTargets.data[renderIndex];
  21872. if (renderTarget._shouldRender()) {
  21873. this._renderId++;
  21874. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21875. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21876. }
  21877. }
  21878. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21879. this._intermediateRendering = false;
  21880. this._renderId++;
  21881. needsRestoreFrameBuffer = true; // Restore back buffer
  21882. }
  21883. // Render HighlightLayer Texture
  21884. var stencilState = this._engine.getStencilBuffer();
  21885. var renderhighlights = false;
  21886. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21887. this._intermediateRendering = true;
  21888. for (var i = 0; i < this.highlightLayers.length; i++) {
  21889. var highlightLayer = this.highlightLayers[i];
  21890. if (highlightLayer.shouldRender() &&
  21891. (!highlightLayer.camera ||
  21892. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21893. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21894. renderhighlights = true;
  21895. var renderTarget = highlightLayer._mainTexture;
  21896. if (renderTarget._shouldRender()) {
  21897. this._renderId++;
  21898. renderTarget.render(false, false);
  21899. needsRestoreFrameBuffer = true;
  21900. }
  21901. }
  21902. }
  21903. this._intermediateRendering = false;
  21904. this._renderId++;
  21905. }
  21906. if (needsRestoreFrameBuffer) {
  21907. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21908. }
  21909. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21910. // Prepare Frame
  21911. this.postProcessManager._prepareFrame();
  21912. // Backgrounds
  21913. var layerIndex;
  21914. var layer;
  21915. if (this.layers.length) {
  21916. engine.setDepthBuffer(false);
  21917. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21918. layer = this.layers[layerIndex];
  21919. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21920. layer.render();
  21921. }
  21922. }
  21923. engine.setDepthBuffer(true);
  21924. }
  21925. // Activate HighlightLayer stencil
  21926. if (renderhighlights) {
  21927. this._engine.setStencilBuffer(true);
  21928. }
  21929. // Render
  21930. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  21931. this._renderingManager.render(null, null, true, true);
  21932. this.onAfterDrawPhaseObservable.notifyObservers(this);
  21933. // Restore HighlightLayer stencil
  21934. if (renderhighlights) {
  21935. this._engine.setStencilBuffer(stencilState);
  21936. }
  21937. // Bounding boxes
  21938. if (this._boundingBoxRenderer) {
  21939. this._boundingBoxRenderer.render();
  21940. }
  21941. // Lens flares
  21942. if (this.lensFlaresEnabled) {
  21943. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21944. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21945. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21946. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21947. lensFlareSystem.render();
  21948. }
  21949. }
  21950. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21951. }
  21952. // Foregrounds
  21953. if (this.layers.length) {
  21954. engine.setDepthBuffer(false);
  21955. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21956. layer = this.layers[layerIndex];
  21957. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21958. layer.render();
  21959. }
  21960. }
  21961. engine.setDepthBuffer(true);
  21962. }
  21963. // Highlight Layer
  21964. if (renderhighlights) {
  21965. engine.setDepthBuffer(false);
  21966. for (var i = 0; i < this.highlightLayers.length; i++) {
  21967. if (this.highlightLayers[i].shouldRender()) {
  21968. this.highlightLayers[i].render();
  21969. }
  21970. }
  21971. engine.setDepthBuffer(true);
  21972. }
  21973. // Finalize frame
  21974. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21975. // Reset some special arrays
  21976. this._renderTargets.reset();
  21977. this._alternateRendering = false;
  21978. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21979. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21980. };
  21981. Scene.prototype._processSubCameras = function (camera) {
  21982. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21983. this._renderForCamera(camera);
  21984. return;
  21985. }
  21986. // Update camera
  21987. if (this.activeCamera) {
  21988. this.activeCamera.update();
  21989. }
  21990. // rig cameras
  21991. for (var index = 0; index < camera._rigCameras.length; index++) {
  21992. this._renderForCamera(camera._rigCameras[index]);
  21993. }
  21994. this.activeCamera = camera;
  21995. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21996. };
  21997. Scene.prototype._checkIntersections = function () {
  21998. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21999. var sourceMesh = this._meshesForIntersections.data[index];
  22000. if (!sourceMesh.actionManager) {
  22001. continue;
  22002. }
  22003. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22004. var action = sourceMesh.actionManager.actions[actionIndex];
  22005. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22006. var parameters = action.getTriggerParameter();
  22007. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22008. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22009. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22010. if (areIntersecting && currentIntersectionInProgress === -1) {
  22011. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22012. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22013. sourceMesh._intersectionsInProgress.push(otherMesh);
  22014. }
  22015. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22016. sourceMesh._intersectionsInProgress.push(otherMesh);
  22017. }
  22018. }
  22019. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22020. //They intersected, and now they don't.
  22021. //is this trigger an exit trigger? execute an event.
  22022. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22023. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22024. }
  22025. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22026. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22027. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22028. }
  22029. }
  22030. }
  22031. }
  22032. }
  22033. };
  22034. Scene.prototype.render = function () {
  22035. if (this.isDisposed) {
  22036. return;
  22037. }
  22038. this._activeParticles.fetchNewFrame();
  22039. this._totalVertices.fetchNewFrame();
  22040. this._activeIndices.fetchNewFrame();
  22041. this._activeBones.fetchNewFrame();
  22042. this._meshesForIntersections.reset();
  22043. this.resetCachedMaterial();
  22044. this.onBeforeAnimationsObservable.notifyObservers(this);
  22045. // Actions
  22046. if (this.actionManager) {
  22047. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22048. }
  22049. //Simplification Queue
  22050. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22051. this.simplificationQueue.executeNext();
  22052. }
  22053. if (this._engine.isDeterministicLockStep()) {
  22054. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22055. var defaultFPS = (60.0 / 1000.0);
  22056. var defaultFrameTime = 1000 / 60; // frame time in MS
  22057. if (this._physicsEngine) {
  22058. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22059. }
  22060. var stepsTaken = 0;
  22061. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22062. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22063. internalSteps = Math.min(internalSteps, maxSubSteps);
  22064. do {
  22065. this.onBeforeStepObservable.notifyObservers(this);
  22066. // Animations
  22067. this._animationRatio = defaultFrameTime * defaultFPS;
  22068. this._animate();
  22069. this.onAfterAnimationsObservable.notifyObservers(this);
  22070. // Physics
  22071. if (this._physicsEngine) {
  22072. this.onBeforePhysicsObservable.notifyObservers(this);
  22073. this._physicsEngine._step(defaultFrameTime / 1000);
  22074. this.onAfterPhysicsObservable.notifyObservers(this);
  22075. }
  22076. this.onAfterStepObservable.notifyObservers(this);
  22077. this._currentStepId++;
  22078. stepsTaken++;
  22079. deltaTime -= defaultFrameTime;
  22080. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22081. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22082. }
  22083. else {
  22084. // Animations
  22085. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22086. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22087. this._animate();
  22088. this.onAfterAnimationsObservable.notifyObservers(this);
  22089. // Physics
  22090. if (this._physicsEngine) {
  22091. this.onBeforePhysicsObservable.notifyObservers(this);
  22092. this._physicsEngine._step(deltaTime / 1000.0);
  22093. this.onAfterPhysicsObservable.notifyObservers(this);
  22094. }
  22095. }
  22096. // update gamepad manager
  22097. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22098. this._gamepadManager._checkGamepadsStatus();
  22099. }
  22100. // Before render
  22101. this.onBeforeRenderObservable.notifyObservers(this);
  22102. // Customs render targets
  22103. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22104. var engine = this.getEngine();
  22105. var currentActiveCamera = this.activeCamera;
  22106. if (this.renderTargetsEnabled) {
  22107. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22108. this._intermediateRendering = true;
  22109. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22110. var renderTarget = this.customRenderTargets[customIndex];
  22111. if (renderTarget._shouldRender()) {
  22112. this._renderId++;
  22113. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22114. if (!this.activeCamera)
  22115. throw new Error("Active camera not set");
  22116. // Viewport
  22117. engine.setViewport(this.activeCamera.viewport);
  22118. // Camera
  22119. this.updateTransformMatrix();
  22120. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22121. }
  22122. }
  22123. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22124. this._intermediateRendering = false;
  22125. this._renderId++;
  22126. }
  22127. // Restore back buffer
  22128. if (this.customRenderTargets.length > 0) {
  22129. engine.restoreDefaultFramebuffer();
  22130. }
  22131. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22132. this.activeCamera = currentActiveCamera;
  22133. // Procedural textures
  22134. if (this.proceduralTexturesEnabled) {
  22135. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22136. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22137. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22138. if (proceduralTexture._shouldRender()) {
  22139. proceduralTexture.render();
  22140. }
  22141. }
  22142. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22143. }
  22144. // Clear
  22145. if (this.autoClearDepthAndStencil || this.autoClear) {
  22146. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22147. }
  22148. // Shadows
  22149. if (this.shadowsEnabled) {
  22150. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22151. var light = this.lights[lightIndex];
  22152. var shadowGenerator = light.getShadowGenerator();
  22153. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22154. var shadowMap = (shadowGenerator.getShadowMap());
  22155. if (this.textures.indexOf(shadowMap) !== -1) {
  22156. this._renderTargets.push(shadowMap);
  22157. }
  22158. }
  22159. }
  22160. }
  22161. // Depth renderer
  22162. if (this._depthRenderer) {
  22163. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22164. }
  22165. // Geometry renderer
  22166. if (this._geometryBufferRenderer) {
  22167. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22168. }
  22169. // RenderPipeline
  22170. if (this._postProcessRenderPipelineManager) {
  22171. this._postProcessRenderPipelineManager.update();
  22172. }
  22173. // Multi-cameras?
  22174. if (this.activeCameras.length > 0) {
  22175. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22176. if (cameraIndex > 0) {
  22177. this._engine.clear(null, false, true, true);
  22178. }
  22179. this._processSubCameras(this.activeCameras[cameraIndex]);
  22180. }
  22181. }
  22182. else {
  22183. if (!this.activeCamera) {
  22184. throw new Error("No camera defined");
  22185. }
  22186. this._processSubCameras(this.activeCamera);
  22187. }
  22188. // Intersection checks
  22189. this._checkIntersections();
  22190. // Update the audio listener attached to the camera
  22191. if (BABYLON.AudioEngine) {
  22192. this._updateAudioParameters();
  22193. }
  22194. // After render
  22195. if (this.afterRender) {
  22196. this.afterRender();
  22197. }
  22198. this.onAfterRenderObservable.notifyObservers(this);
  22199. // Cleaning
  22200. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22201. var data = this._toBeDisposed.data[index];
  22202. if (data) {
  22203. data.dispose();
  22204. }
  22205. this._toBeDisposed[index] = null;
  22206. }
  22207. this._toBeDisposed.reset();
  22208. if (this.dumpNextRenderTargets) {
  22209. this.dumpNextRenderTargets = false;
  22210. }
  22211. this._activeBones.addCount(0, true);
  22212. this._activeIndices.addCount(0, true);
  22213. this._activeParticles.addCount(0, true);
  22214. };
  22215. Scene.prototype._updateAudioParameters = function () {
  22216. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22217. return;
  22218. }
  22219. var listeningCamera;
  22220. var audioEngine = BABYLON.Engine.audioEngine;
  22221. if (this.activeCameras.length > 0) {
  22222. listeningCamera = this.activeCameras[0];
  22223. }
  22224. else {
  22225. listeningCamera = this.activeCamera;
  22226. }
  22227. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22228. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22229. // for VR cameras
  22230. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22231. listeningCamera = listeningCamera.rigCameras[0];
  22232. }
  22233. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22234. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22235. cameraDirection.normalize();
  22236. // To avoid some errors on GearVR
  22237. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22238. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22239. }
  22240. var i;
  22241. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22242. var sound = this.mainSoundTrack.soundCollection[i];
  22243. if (sound.useCustomAttenuation) {
  22244. sound.updateDistanceFromListener();
  22245. }
  22246. }
  22247. for (i = 0; i < this.soundTracks.length; i++) {
  22248. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22249. sound = this.soundTracks[i].soundCollection[j];
  22250. if (sound.useCustomAttenuation) {
  22251. sound.updateDistanceFromListener();
  22252. }
  22253. }
  22254. }
  22255. }
  22256. };
  22257. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22258. // Audio
  22259. get: function () {
  22260. return this._audioEnabled;
  22261. },
  22262. set: function (value) {
  22263. this._audioEnabled = value;
  22264. if (BABYLON.AudioEngine) {
  22265. if (this._audioEnabled) {
  22266. this._enableAudio();
  22267. }
  22268. else {
  22269. this._disableAudio();
  22270. }
  22271. }
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Scene.prototype._disableAudio = function () {
  22277. var i;
  22278. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22279. this.mainSoundTrack.soundCollection[i].pause();
  22280. }
  22281. for (i = 0; i < this.soundTracks.length; i++) {
  22282. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22283. this.soundTracks[i].soundCollection[j].pause();
  22284. }
  22285. }
  22286. };
  22287. Scene.prototype._enableAudio = function () {
  22288. var i;
  22289. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22290. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22291. this.mainSoundTrack.soundCollection[i].play();
  22292. }
  22293. }
  22294. for (i = 0; i < this.soundTracks.length; i++) {
  22295. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22296. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22297. this.soundTracks[i].soundCollection[j].play();
  22298. }
  22299. }
  22300. }
  22301. };
  22302. Object.defineProperty(Scene.prototype, "headphone", {
  22303. get: function () {
  22304. return this._headphone;
  22305. },
  22306. set: function (value) {
  22307. this._headphone = value;
  22308. if (BABYLON.AudioEngine) {
  22309. if (this._headphone) {
  22310. this._switchAudioModeForHeadphones();
  22311. }
  22312. else {
  22313. this._switchAudioModeForNormalSpeakers();
  22314. }
  22315. }
  22316. },
  22317. enumerable: true,
  22318. configurable: true
  22319. });
  22320. Scene.prototype._switchAudioModeForHeadphones = function () {
  22321. this.mainSoundTrack.switchPanningModelToHRTF();
  22322. for (var i = 0; i < this.soundTracks.length; i++) {
  22323. this.soundTracks[i].switchPanningModelToHRTF();
  22324. }
  22325. };
  22326. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22327. this.mainSoundTrack.switchPanningModelToEqualPower();
  22328. for (var i = 0; i < this.soundTracks.length; i++) {
  22329. this.soundTracks[i].switchPanningModelToEqualPower();
  22330. }
  22331. };
  22332. Scene.prototype.enableDepthRenderer = function () {
  22333. if (this._depthRenderer) {
  22334. return this._depthRenderer;
  22335. }
  22336. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22337. return this._depthRenderer;
  22338. };
  22339. Scene.prototype.disableDepthRenderer = function () {
  22340. if (!this._depthRenderer) {
  22341. return;
  22342. }
  22343. this._depthRenderer.dispose();
  22344. this._depthRenderer = null;
  22345. };
  22346. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22347. if (ratio === void 0) { ratio = 1; }
  22348. if (this._geometryBufferRenderer) {
  22349. return this._geometryBufferRenderer;
  22350. }
  22351. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22352. if (!this._geometryBufferRenderer.isSupported) {
  22353. this._geometryBufferRenderer = null;
  22354. }
  22355. return this._geometryBufferRenderer;
  22356. };
  22357. Scene.prototype.disableGeometryBufferRenderer = function () {
  22358. if (!this._geometryBufferRenderer) {
  22359. return;
  22360. }
  22361. this._geometryBufferRenderer.dispose();
  22362. this._geometryBufferRenderer = null;
  22363. };
  22364. Scene.prototype.freezeMaterials = function () {
  22365. for (var i = 0; i < this.materials.length; i++) {
  22366. this.materials[i].freeze();
  22367. }
  22368. };
  22369. Scene.prototype.unfreezeMaterials = function () {
  22370. for (var i = 0; i < this.materials.length; i++) {
  22371. this.materials[i].unfreeze();
  22372. }
  22373. };
  22374. Scene.prototype.dispose = function () {
  22375. this.beforeRender = null;
  22376. this.afterRender = null;
  22377. this.skeletons = [];
  22378. this.morphTargetManagers = [];
  22379. this.importedMeshesFiles = new Array();
  22380. this.stopAllAnimations();
  22381. this.resetCachedMaterial();
  22382. if (this._depthRenderer) {
  22383. this._depthRenderer.dispose();
  22384. }
  22385. if (this._gamepadManager) {
  22386. this._gamepadManager.dispose();
  22387. this._gamepadManager = null;
  22388. }
  22389. // Smart arrays
  22390. if (this.activeCamera) {
  22391. this.activeCamera._activeMeshes.dispose();
  22392. this.activeCamera = null;
  22393. }
  22394. this._activeMeshes.dispose();
  22395. this._renderingManager.dispose();
  22396. this._processedMaterials.dispose();
  22397. this._activeParticleSystems.dispose();
  22398. this._activeSkeletons.dispose();
  22399. this._softwareSkinnedMeshes.dispose();
  22400. this._renderTargets.dispose();
  22401. if (this._boundingBoxRenderer) {
  22402. this._boundingBoxRenderer.dispose();
  22403. }
  22404. this._meshesForIntersections.dispose();
  22405. this._toBeDisposed.dispose();
  22406. // Abort active requests
  22407. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22408. var request = _a[_i];
  22409. request.abort();
  22410. }
  22411. // Debug layer
  22412. if (this._debugLayer) {
  22413. this._debugLayer.hide();
  22414. }
  22415. // Events
  22416. this.onDisposeObservable.notifyObservers(this);
  22417. this.onDisposeObservable.clear();
  22418. this.onBeforeRenderObservable.clear();
  22419. this.onAfterRenderObservable.clear();
  22420. this.OnBeforeRenderTargetsRenderObservable.clear();
  22421. this.OnAfterRenderTargetsRenderObservable.clear();
  22422. this.onAfterStepObservable.clear();
  22423. this.onBeforeStepObservable.clear();
  22424. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22425. this.onAfterActiveMeshesEvaluationObservable.clear();
  22426. this.onBeforeParticlesRenderingObservable.clear();
  22427. this.onAfterParticlesRenderingObservable.clear();
  22428. this.onBeforeSpritesRenderingObservable.clear();
  22429. this.onAfterSpritesRenderingObservable.clear();
  22430. this.onBeforeDrawPhaseObservable.clear();
  22431. this.onAfterDrawPhaseObservable.clear();
  22432. this.onBeforePhysicsObservable.clear();
  22433. this.onAfterPhysicsObservable.clear();
  22434. this.onBeforeAnimationsObservable.clear();
  22435. this.onAfterAnimationsObservable.clear();
  22436. this.onDataLoadedObservable.clear();
  22437. this.detachControl();
  22438. // Release sounds & sounds tracks
  22439. if (BABYLON.AudioEngine) {
  22440. this.disposeSounds();
  22441. }
  22442. // VR Helper
  22443. if (this.VRHelper) {
  22444. this.VRHelper.dispose();
  22445. }
  22446. // Detach cameras
  22447. var canvas = this._engine.getRenderingCanvas();
  22448. if (canvas) {
  22449. var index;
  22450. for (index = 0; index < this.cameras.length; index++) {
  22451. this.cameras[index].detachControl(canvas);
  22452. }
  22453. }
  22454. // Release animation groups
  22455. while (this.animationGroups.length) {
  22456. this.animationGroups[0].dispose();
  22457. }
  22458. // Release lights
  22459. while (this.lights.length) {
  22460. this.lights[0].dispose();
  22461. }
  22462. // Release meshes
  22463. while (this.meshes.length) {
  22464. this.meshes[0].dispose(true);
  22465. }
  22466. while (this.transformNodes.length) {
  22467. this.removeTransformNode(this.transformNodes[0]);
  22468. }
  22469. // Release cameras
  22470. while (this.cameras.length) {
  22471. this.cameras[0].dispose();
  22472. }
  22473. // Release materials
  22474. if (this.defaultMaterial) {
  22475. this.defaultMaterial.dispose();
  22476. }
  22477. while (this.multiMaterials.length) {
  22478. this.multiMaterials[0].dispose();
  22479. }
  22480. while (this.materials.length) {
  22481. this.materials[0].dispose();
  22482. }
  22483. // Release particles
  22484. while (this.particleSystems.length) {
  22485. this.particleSystems[0].dispose();
  22486. }
  22487. // Release sprites
  22488. while (this.spriteManagers.length) {
  22489. this.spriteManagers[0].dispose();
  22490. }
  22491. // Release postProcesses
  22492. while (this.postProcesses.length) {
  22493. this.postProcesses[0].dispose();
  22494. }
  22495. // Release layers
  22496. while (this.layers.length) {
  22497. this.layers[0].dispose();
  22498. }
  22499. while (this.highlightLayers.length) {
  22500. this.highlightLayers[0].dispose();
  22501. }
  22502. // Release textures
  22503. while (this.textures.length) {
  22504. this.textures[0].dispose();
  22505. }
  22506. // Release UBO
  22507. this._sceneUbo.dispose();
  22508. if (this._alternateSceneUbo) {
  22509. this._alternateSceneUbo.dispose();
  22510. }
  22511. // Post-processes
  22512. this.postProcessManager.dispose();
  22513. if (this._postProcessRenderPipelineManager) {
  22514. this._postProcessRenderPipelineManager.dispose();
  22515. }
  22516. // Physics
  22517. if (this._physicsEngine) {
  22518. this.disablePhysicsEngine();
  22519. }
  22520. // Remove from engine
  22521. index = this._engine.scenes.indexOf(this);
  22522. if (index > -1) {
  22523. this._engine.scenes.splice(index, 1);
  22524. }
  22525. this._engine.wipeCaches(true);
  22526. this._isDisposed = true;
  22527. };
  22528. Object.defineProperty(Scene.prototype, "isDisposed", {
  22529. get: function () {
  22530. return this._isDisposed;
  22531. },
  22532. enumerable: true,
  22533. configurable: true
  22534. });
  22535. // Release sounds & sounds tracks
  22536. Scene.prototype.disposeSounds = function () {
  22537. if (!this._mainSoundTrack) {
  22538. return;
  22539. }
  22540. this.mainSoundTrack.dispose();
  22541. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22542. this.soundTracks[scIndex].dispose();
  22543. }
  22544. };
  22545. // Octrees
  22546. Scene.prototype.getWorldExtends = function () {
  22547. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22548. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22549. for (var index = 0; index < this.meshes.length; index++) {
  22550. var mesh = this.meshes[index];
  22551. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22552. continue;
  22553. }
  22554. mesh.computeWorldMatrix(true);
  22555. var boundingInfo = mesh.getBoundingInfo();
  22556. var minBox = boundingInfo.boundingBox.minimumWorld;
  22557. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22558. BABYLON.Tools.CheckExtends(minBox, min, max);
  22559. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22560. }
  22561. return {
  22562. min: min,
  22563. max: max
  22564. };
  22565. };
  22566. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22567. if (maxCapacity === void 0) { maxCapacity = 64; }
  22568. if (maxDepth === void 0) { maxDepth = 2; }
  22569. if (!this._selectionOctree) {
  22570. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22571. }
  22572. var worldExtends = this.getWorldExtends();
  22573. // Update octree
  22574. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22575. return this._selectionOctree;
  22576. };
  22577. // Picking
  22578. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22579. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22580. var result = BABYLON.Ray.Zero();
  22581. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22582. return result;
  22583. };
  22584. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22585. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22586. var engine = this._engine;
  22587. if (!camera) {
  22588. if (!this.activeCamera)
  22589. throw new Error("Active camera not set");
  22590. camera = this.activeCamera;
  22591. }
  22592. var cameraViewport = camera.viewport;
  22593. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22594. // Moving coordinates to local viewport world
  22595. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22596. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22597. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22598. return this;
  22599. };
  22600. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22601. var result = BABYLON.Ray.Zero();
  22602. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22603. return result;
  22604. };
  22605. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22606. if (!BABYLON.PickingInfo) {
  22607. return this;
  22608. }
  22609. var engine = this._engine;
  22610. if (!camera) {
  22611. if (!this.activeCamera)
  22612. throw new Error("Active camera not set");
  22613. camera = this.activeCamera;
  22614. }
  22615. var cameraViewport = camera.viewport;
  22616. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22617. var identity = BABYLON.Matrix.Identity();
  22618. // Moving coordinates to local viewport world
  22619. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22620. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22621. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22622. return this;
  22623. };
  22624. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22625. if (!BABYLON.PickingInfo) {
  22626. return null;
  22627. }
  22628. var pickingInfo = null;
  22629. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22630. var mesh = this.meshes[meshIndex];
  22631. if (predicate) {
  22632. if (!predicate(mesh)) {
  22633. continue;
  22634. }
  22635. }
  22636. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22637. continue;
  22638. }
  22639. var world = mesh.getWorldMatrix();
  22640. var ray = rayFunction(world);
  22641. var result = mesh.intersects(ray, fastCheck);
  22642. if (!result || !result.hit)
  22643. continue;
  22644. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22645. continue;
  22646. pickingInfo = result;
  22647. if (fastCheck) {
  22648. break;
  22649. }
  22650. }
  22651. return pickingInfo || new BABYLON.PickingInfo();
  22652. };
  22653. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22654. if (!BABYLON.PickingInfo) {
  22655. return null;
  22656. }
  22657. var pickingInfos = new Array();
  22658. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22659. var mesh = this.meshes[meshIndex];
  22660. if (predicate) {
  22661. if (!predicate(mesh)) {
  22662. continue;
  22663. }
  22664. }
  22665. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22666. continue;
  22667. }
  22668. var world = mesh.getWorldMatrix();
  22669. var ray = rayFunction(world);
  22670. var result = mesh.intersects(ray, false);
  22671. if (!result || !result.hit)
  22672. continue;
  22673. pickingInfos.push(result);
  22674. }
  22675. return pickingInfos;
  22676. };
  22677. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22678. if (!BABYLON.PickingInfo) {
  22679. return null;
  22680. }
  22681. var pickingInfo = null;
  22682. if (!camera) {
  22683. if (!this.activeCamera) {
  22684. return null;
  22685. }
  22686. camera = this.activeCamera;
  22687. }
  22688. if (this.spriteManagers.length > 0) {
  22689. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22690. var spriteManager = this.spriteManagers[spriteIndex];
  22691. if (!spriteManager.isPickable) {
  22692. continue;
  22693. }
  22694. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22695. if (!result || !result.hit)
  22696. continue;
  22697. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22698. continue;
  22699. pickingInfo = result;
  22700. if (fastCheck) {
  22701. break;
  22702. }
  22703. }
  22704. }
  22705. return pickingInfo || new BABYLON.PickingInfo();
  22706. };
  22707. /** Launch a ray to try to pick a mesh in the scene
  22708. * @param x position on screen
  22709. * @param y position on screen
  22710. * @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
  22711. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22712. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22713. */
  22714. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22715. var _this = this;
  22716. if (!BABYLON.PickingInfo) {
  22717. return null;
  22718. }
  22719. return this._internalPick(function (world) {
  22720. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22721. return _this._tempPickingRay;
  22722. }, predicate, fastCheck);
  22723. };
  22724. /** Launch a ray to try to pick a sprite in the scene
  22725. * @param x position on screen
  22726. * @param y position on screen
  22727. * @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
  22728. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22729. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22730. */
  22731. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22732. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22733. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22734. };
  22735. /** Use the given ray to pick a mesh in the scene
  22736. * @param ray The ray to use to pick meshes
  22737. * @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
  22738. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22739. */
  22740. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22741. var _this = this;
  22742. return this._internalPick(function (world) {
  22743. if (!_this._pickWithRayInverseMatrix) {
  22744. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22745. }
  22746. world.invertToRef(_this._pickWithRayInverseMatrix);
  22747. if (!_this._cachedRayForTransform) {
  22748. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22749. }
  22750. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22751. return _this._cachedRayForTransform;
  22752. }, predicate, fastCheck);
  22753. };
  22754. /**
  22755. * Launch a ray to try to pick a mesh in the scene
  22756. * @param x X position on screen
  22757. * @param y Y position on screen
  22758. * @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
  22759. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22760. */
  22761. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22762. var _this = this;
  22763. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22764. };
  22765. /**
  22766. * Launch a ray to try to pick a mesh in the scene
  22767. * @param ray Ray to use
  22768. * @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
  22769. */
  22770. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22771. var _this = this;
  22772. return this._internalMultiPick(function (world) {
  22773. if (!_this._pickWithRayInverseMatrix) {
  22774. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22775. }
  22776. world.invertToRef(_this._pickWithRayInverseMatrix);
  22777. if (!_this._cachedRayForTransform) {
  22778. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22779. }
  22780. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22781. return _this._cachedRayForTransform;
  22782. }, predicate);
  22783. };
  22784. Scene.prototype.setPointerOverMesh = function (mesh) {
  22785. if (this._pointerOverMesh === mesh) {
  22786. return;
  22787. }
  22788. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22789. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22790. }
  22791. this._pointerOverMesh = mesh;
  22792. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22793. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22794. }
  22795. };
  22796. Scene.prototype.getPointerOverMesh = function () {
  22797. return this._pointerOverMesh;
  22798. };
  22799. Scene.prototype.setPointerOverSprite = function (sprite) {
  22800. if (this._pointerOverSprite === sprite) {
  22801. return;
  22802. }
  22803. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22804. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22805. }
  22806. this._pointerOverSprite = sprite;
  22807. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22808. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22809. }
  22810. };
  22811. Scene.prototype.getPointerOverSprite = function () {
  22812. return this._pointerOverSprite;
  22813. };
  22814. // Physics
  22815. Scene.prototype.getPhysicsEngine = function () {
  22816. return this._physicsEngine;
  22817. };
  22818. /**
  22819. * Enables physics to the current scene
  22820. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22821. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22822. * @return {boolean} was the physics engine initialized
  22823. */
  22824. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22825. if (gravity === void 0) { gravity = null; }
  22826. if (this._physicsEngine) {
  22827. return true;
  22828. }
  22829. try {
  22830. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22831. return true;
  22832. }
  22833. catch (e) {
  22834. BABYLON.Tools.Error(e.message);
  22835. return false;
  22836. }
  22837. };
  22838. Scene.prototype.disablePhysicsEngine = function () {
  22839. if (!this._physicsEngine) {
  22840. return;
  22841. }
  22842. this._physicsEngine.dispose();
  22843. this._physicsEngine = null;
  22844. };
  22845. Scene.prototype.isPhysicsEnabled = function () {
  22846. return this._physicsEngine !== undefined;
  22847. };
  22848. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22849. var mesh = compound.parts[0].mesh;
  22850. if (mesh.physicsImpostor) {
  22851. mesh.physicsImpostor.dispose();
  22852. mesh.physicsImpostor = null;
  22853. }
  22854. };
  22855. // Misc.
  22856. Scene.prototype._rebuildGeometries = function () {
  22857. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22858. var geometry = _a[_i];
  22859. geometry._rebuild();
  22860. }
  22861. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22862. var mesh = _c[_b];
  22863. mesh._rebuild();
  22864. }
  22865. if (this.postProcessManager) {
  22866. this.postProcessManager._rebuild();
  22867. }
  22868. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22869. var layer = _e[_d];
  22870. layer._rebuild();
  22871. }
  22872. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22873. var highlightLayer = _g[_f];
  22874. highlightLayer._rebuild();
  22875. }
  22876. if (this._boundingBoxRenderer) {
  22877. this._boundingBoxRenderer._rebuild();
  22878. }
  22879. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22880. var system = _j[_h];
  22881. system.rebuild();
  22882. }
  22883. if (this._postProcessRenderPipelineManager) {
  22884. this._postProcessRenderPipelineManager._rebuild();
  22885. }
  22886. };
  22887. Scene.prototype._rebuildTextures = function () {
  22888. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22889. var texture = _a[_i];
  22890. texture._rebuild();
  22891. }
  22892. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22893. };
  22894. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22895. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22896. if (replace === void 0) { replace = false; }
  22897. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22898. // Dispose existing camera or light in replace mode.
  22899. if (replace) {
  22900. if (this.activeCamera) {
  22901. this.activeCamera.dispose();
  22902. this.activeCamera = null;
  22903. }
  22904. if (this.lights) {
  22905. for (var i = 0; i < this.lights.length; i++) {
  22906. this.lights[i].dispose();
  22907. }
  22908. }
  22909. }
  22910. // Light
  22911. if (this.lights.length === 0) {
  22912. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22913. }
  22914. // Camera
  22915. if (!this.activeCamera) {
  22916. var worldExtends = this.getWorldExtends();
  22917. var worldSize = worldExtends.max.subtract(worldExtends.min);
  22918. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  22919. var camera;
  22920. var radius = worldSize.length() * 1.5;
  22921. if (createArcRotateCamera) {
  22922. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  22923. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  22924. arcRotateCamera.wheelPrecision = 100 / radius;
  22925. camera = arcRotateCamera;
  22926. }
  22927. else {
  22928. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  22929. freeCamera.setTarget(worldCenter);
  22930. camera = freeCamera;
  22931. }
  22932. camera.minZ = radius * 0.01;
  22933. camera.maxZ = radius * 1000;
  22934. camera.speed = radius * 0.2;
  22935. this.activeCamera = camera;
  22936. var canvas = this.getEngine().getRenderingCanvas();
  22937. if (attachCameraControls && canvas) {
  22938. camera.attachControl(canvas);
  22939. }
  22940. }
  22941. };
  22942. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  22943. if (pbr === void 0) { pbr = false; }
  22944. if (scale === void 0) { scale = 1000; }
  22945. if (blur === void 0) { blur = 0; }
  22946. if (environmentTexture) {
  22947. this.environmentTexture = environmentTexture;
  22948. }
  22949. if (!this.environmentTexture) {
  22950. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  22951. return null;
  22952. }
  22953. // Skybox
  22954. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  22955. if (pbr) {
  22956. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22957. hdrSkyboxMaterial.backFaceCulling = false;
  22958. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22959. if (hdrSkyboxMaterial.reflectionTexture) {
  22960. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22961. }
  22962. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22963. hdrSkyboxMaterial.disableLighting = true;
  22964. hdrSkyboxMaterial.twoSidedLighting = true;
  22965. hdrSkybox.infiniteDistance = true;
  22966. hdrSkybox.material = hdrSkyboxMaterial;
  22967. }
  22968. else {
  22969. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22970. skyboxMaterial.backFaceCulling = false;
  22971. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22972. if (skyboxMaterial.reflectionTexture) {
  22973. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22974. }
  22975. skyboxMaterial.disableLighting = true;
  22976. hdrSkybox.infiniteDistance = true;
  22977. hdrSkybox.material = skyboxMaterial;
  22978. }
  22979. return hdrSkybox;
  22980. };
  22981. Scene.prototype.createDefaultEnvironment = function (options) {
  22982. if (BABYLON.EnvironmentHelper) {
  22983. return new BABYLON.EnvironmentHelper(options, this);
  22984. }
  22985. return null;
  22986. };
  22987. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22988. if (webVROptions === void 0) { webVROptions = {}; }
  22989. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22990. };
  22991. // Tags
  22992. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22993. if (tagsQuery === undefined) {
  22994. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22995. return list;
  22996. }
  22997. var listByTags = [];
  22998. forEach = forEach || (function (item) { return; });
  22999. for (var i in list) {
  23000. var item = list[i];
  23001. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23002. listByTags.push(item);
  23003. forEach(item);
  23004. }
  23005. }
  23006. return listByTags;
  23007. };
  23008. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23009. return this._getByTags(this.meshes, tagsQuery, forEach);
  23010. };
  23011. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23012. return this._getByTags(this.cameras, tagsQuery, forEach);
  23013. };
  23014. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23015. return this._getByTags(this.lights, tagsQuery, forEach);
  23016. };
  23017. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23018. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23019. };
  23020. /**
  23021. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23022. * This allowed control for front to back rendering or reversly depending of the special needs.
  23023. *
  23024. * @param renderingGroupId The rendering group id corresponding to its index
  23025. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23026. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23027. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23028. */
  23029. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23030. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23031. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23032. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23033. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23034. };
  23035. /**
  23036. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23037. *
  23038. * @param renderingGroupId The rendering group id corresponding to its index
  23039. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23040. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23041. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23042. */
  23043. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23044. if (depth === void 0) { depth = true; }
  23045. if (stencil === void 0) { stencil = true; }
  23046. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23047. };
  23048. /**
  23049. * Will flag all materials as dirty to trigger new shader compilation
  23050. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23051. */
  23052. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23053. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23054. var material = _a[_i];
  23055. if (predicate && !predicate(material)) {
  23056. continue;
  23057. }
  23058. material.markAsDirty(flag);
  23059. }
  23060. };
  23061. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23062. var _this = this;
  23063. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23064. this._activeRequests.push(request);
  23065. request.onCompleteObservable.add(function (request) {
  23066. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23067. });
  23068. return request;
  23069. };
  23070. // Statics
  23071. Scene._FOGMODE_NONE = 0;
  23072. Scene._FOGMODE_EXP = 1;
  23073. Scene._FOGMODE_EXP2 = 2;
  23074. Scene._FOGMODE_LINEAR = 3;
  23075. Scene._uniqueIdCounter = 0;
  23076. Scene.MinDeltaTime = 1.0;
  23077. Scene.MaxDeltaTime = 1000.0;
  23078. /** The distance in pixel that you have to move to prevent some events */
  23079. Scene.DragMovementThreshold = 10; // in pixels
  23080. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23081. Scene.LongPressDelay = 500; // in milliseconds
  23082. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23083. Scene.DoubleClickDelay = 300; // in milliseconds
  23084. /** If you need to check double click without raising a single click at first click, enable this flag */
  23085. Scene.ExclusiveDoubleClickMode = false;
  23086. return Scene;
  23087. }());
  23088. BABYLON.Scene = Scene;
  23089. })(BABYLON || (BABYLON = {}));
  23090. //# sourceMappingURL=babylon.scene.js.map
  23091. var BABYLON;
  23092. (function (BABYLON) {
  23093. var Buffer = /** @class */ (function () {
  23094. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23095. if (instanced === void 0) { instanced = false; }
  23096. if (engine instanceof BABYLON.Mesh) {
  23097. this._engine = engine.getScene().getEngine();
  23098. }
  23099. else {
  23100. this._engine = engine;
  23101. }
  23102. this._updatable = updatable;
  23103. this._data = data;
  23104. this._strideSize = stride;
  23105. if (!postponeInternalCreation) {
  23106. this.create();
  23107. }
  23108. this._instanced = instanced;
  23109. this._instanceDivisor = instanced ? 1 : 0;
  23110. }
  23111. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23112. // a lot of these parameters are ignored as they are overriden by the buffer
  23113. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23114. };
  23115. // Properties
  23116. Buffer.prototype.isUpdatable = function () {
  23117. return this._updatable;
  23118. };
  23119. Buffer.prototype.getData = function () {
  23120. return this._data;
  23121. };
  23122. Buffer.prototype.getBuffer = function () {
  23123. return this._buffer;
  23124. };
  23125. Buffer.prototype.getStrideSize = function () {
  23126. return this._strideSize;
  23127. };
  23128. Buffer.prototype.getIsInstanced = function () {
  23129. return this._instanced;
  23130. };
  23131. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23132. get: function () {
  23133. return this._instanceDivisor;
  23134. },
  23135. set: function (value) {
  23136. this._instanceDivisor = value;
  23137. if (value == 0) {
  23138. this._instanced = false;
  23139. }
  23140. else {
  23141. this._instanced = true;
  23142. }
  23143. },
  23144. enumerable: true,
  23145. configurable: true
  23146. });
  23147. // Methods
  23148. Buffer.prototype.create = function (data) {
  23149. if (data === void 0) { data = null; }
  23150. if (!data && this._buffer) {
  23151. return; // nothing to do
  23152. }
  23153. data = data || this._data;
  23154. if (!data) {
  23155. return;
  23156. }
  23157. if (!this._buffer) {
  23158. if (this._updatable) {
  23159. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23160. this._data = data;
  23161. }
  23162. else {
  23163. this._buffer = this._engine.createVertexBuffer(data);
  23164. }
  23165. }
  23166. else if (this._updatable) {
  23167. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23168. this._data = data;
  23169. }
  23170. };
  23171. Buffer.prototype._rebuild = function () {
  23172. this._buffer = null;
  23173. this.create(this._data);
  23174. };
  23175. Buffer.prototype.update = function (data) {
  23176. this.create(data);
  23177. };
  23178. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23179. if (!this._buffer) {
  23180. return;
  23181. }
  23182. if (this._updatable) {
  23183. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23184. this._data = null;
  23185. }
  23186. };
  23187. Buffer.prototype.dispose = function () {
  23188. if (!this._buffer) {
  23189. return;
  23190. }
  23191. if (this._engine._releaseBuffer(this._buffer)) {
  23192. this._buffer = null;
  23193. }
  23194. };
  23195. return Buffer;
  23196. }());
  23197. BABYLON.Buffer = Buffer;
  23198. })(BABYLON || (BABYLON = {}));
  23199. //# sourceMappingURL=babylon.buffer.js.map
  23200. var BABYLON;
  23201. (function (BABYLON) {
  23202. var VertexBuffer = /** @class */ (function () {
  23203. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23204. if (!stride) {
  23205. // Deduce stride from kind
  23206. switch (kind) {
  23207. case VertexBuffer.PositionKind:
  23208. stride = 3;
  23209. break;
  23210. case VertexBuffer.NormalKind:
  23211. stride = 3;
  23212. break;
  23213. case VertexBuffer.UVKind:
  23214. case VertexBuffer.UV2Kind:
  23215. case VertexBuffer.UV3Kind:
  23216. case VertexBuffer.UV4Kind:
  23217. case VertexBuffer.UV5Kind:
  23218. case VertexBuffer.UV6Kind:
  23219. stride = 2;
  23220. break;
  23221. case VertexBuffer.TangentKind:
  23222. case VertexBuffer.ColorKind:
  23223. stride = 4;
  23224. break;
  23225. case VertexBuffer.MatricesIndicesKind:
  23226. case VertexBuffer.MatricesIndicesExtraKind:
  23227. stride = 4;
  23228. break;
  23229. case VertexBuffer.MatricesWeightsKind:
  23230. case VertexBuffer.MatricesWeightsExtraKind:
  23231. default:
  23232. stride = 4;
  23233. break;
  23234. }
  23235. }
  23236. if (data instanceof BABYLON.Buffer) {
  23237. if (!stride) {
  23238. stride = data.getStrideSize();
  23239. }
  23240. this._buffer = data;
  23241. this._ownsBuffer = false;
  23242. }
  23243. else {
  23244. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23245. this._ownsBuffer = true;
  23246. }
  23247. this._stride = stride;
  23248. this._offset = offset ? offset : 0;
  23249. this._size = size ? size : stride;
  23250. this._kind = kind;
  23251. }
  23252. VertexBuffer.prototype._rebuild = function () {
  23253. if (!this._buffer) {
  23254. return;
  23255. }
  23256. this._buffer._rebuild();
  23257. };
  23258. /**
  23259. * Returns the kind of the VertexBuffer (string).
  23260. */
  23261. VertexBuffer.prototype.getKind = function () {
  23262. return this._kind;
  23263. };
  23264. // Properties
  23265. /**
  23266. * Boolean : is the VertexBuffer updatable ?
  23267. */
  23268. VertexBuffer.prototype.isUpdatable = function () {
  23269. return this._buffer.isUpdatable();
  23270. };
  23271. /**
  23272. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23273. */
  23274. VertexBuffer.prototype.getData = function () {
  23275. return this._buffer.getData();
  23276. };
  23277. /**
  23278. * Returns the WebGLBuffer associated to the VertexBuffer.
  23279. */
  23280. VertexBuffer.prototype.getBuffer = function () {
  23281. return this._buffer.getBuffer();
  23282. };
  23283. /**
  23284. * Returns the stride of the VertexBuffer (integer).
  23285. */
  23286. VertexBuffer.prototype.getStrideSize = function () {
  23287. return this._stride;
  23288. };
  23289. /**
  23290. * Returns the offset (integer).
  23291. */
  23292. VertexBuffer.prototype.getOffset = function () {
  23293. return this._offset;
  23294. };
  23295. /**
  23296. * Returns the VertexBuffer total size (integer).
  23297. */
  23298. VertexBuffer.prototype.getSize = function () {
  23299. return this._size;
  23300. };
  23301. /**
  23302. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23303. */
  23304. VertexBuffer.prototype.getIsInstanced = function () {
  23305. return this._buffer.getIsInstanced();
  23306. };
  23307. /**
  23308. * Returns the instancing divisor, zero for non-instanced (integer).
  23309. */
  23310. VertexBuffer.prototype.getInstanceDivisor = function () {
  23311. return this._buffer.instanceDivisor;
  23312. };
  23313. // Methods
  23314. /**
  23315. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23316. * Returns the created WebGLBuffer.
  23317. */
  23318. VertexBuffer.prototype.create = function (data) {
  23319. return this._buffer.create(data);
  23320. };
  23321. /**
  23322. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23323. * Returns the updated WebGLBuffer.
  23324. */
  23325. VertexBuffer.prototype.update = function (data) {
  23326. return this._buffer.update(data);
  23327. };
  23328. /**
  23329. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23330. * Returns the directly updated WebGLBuffer.
  23331. */
  23332. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23333. return this._buffer.updateDirectly(data, offset);
  23334. };
  23335. /**
  23336. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23337. */
  23338. VertexBuffer.prototype.dispose = function () {
  23339. if (this._ownsBuffer) {
  23340. this._buffer.dispose();
  23341. }
  23342. };
  23343. Object.defineProperty(VertexBuffer, "PositionKind", {
  23344. get: function () {
  23345. return VertexBuffer._PositionKind;
  23346. },
  23347. enumerable: true,
  23348. configurable: true
  23349. });
  23350. Object.defineProperty(VertexBuffer, "NormalKind", {
  23351. get: function () {
  23352. return VertexBuffer._NormalKind;
  23353. },
  23354. enumerable: true,
  23355. configurable: true
  23356. });
  23357. Object.defineProperty(VertexBuffer, "TangentKind", {
  23358. get: function () {
  23359. return VertexBuffer._TangentKind;
  23360. },
  23361. enumerable: true,
  23362. configurable: true
  23363. });
  23364. Object.defineProperty(VertexBuffer, "UVKind", {
  23365. get: function () {
  23366. return VertexBuffer._UVKind;
  23367. },
  23368. enumerable: true,
  23369. configurable: true
  23370. });
  23371. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23372. get: function () {
  23373. return VertexBuffer._UV2Kind;
  23374. },
  23375. enumerable: true,
  23376. configurable: true
  23377. });
  23378. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23379. get: function () {
  23380. return VertexBuffer._UV3Kind;
  23381. },
  23382. enumerable: true,
  23383. configurable: true
  23384. });
  23385. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23386. get: function () {
  23387. return VertexBuffer._UV4Kind;
  23388. },
  23389. enumerable: true,
  23390. configurable: true
  23391. });
  23392. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23393. get: function () {
  23394. return VertexBuffer._UV5Kind;
  23395. },
  23396. enumerable: true,
  23397. configurable: true
  23398. });
  23399. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23400. get: function () {
  23401. return VertexBuffer._UV6Kind;
  23402. },
  23403. enumerable: true,
  23404. configurable: true
  23405. });
  23406. Object.defineProperty(VertexBuffer, "ColorKind", {
  23407. get: function () {
  23408. return VertexBuffer._ColorKind;
  23409. },
  23410. enumerable: true,
  23411. configurable: true
  23412. });
  23413. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23414. get: function () {
  23415. return VertexBuffer._MatricesIndicesKind;
  23416. },
  23417. enumerable: true,
  23418. configurable: true
  23419. });
  23420. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23421. get: function () {
  23422. return VertexBuffer._MatricesWeightsKind;
  23423. },
  23424. enumerable: true,
  23425. configurable: true
  23426. });
  23427. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23428. get: function () {
  23429. return VertexBuffer._MatricesIndicesExtraKind;
  23430. },
  23431. enumerable: true,
  23432. configurable: true
  23433. });
  23434. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23435. get: function () {
  23436. return VertexBuffer._MatricesWeightsExtraKind;
  23437. },
  23438. enumerable: true,
  23439. configurable: true
  23440. });
  23441. // Enums
  23442. VertexBuffer._PositionKind = "position";
  23443. VertexBuffer._NormalKind = "normal";
  23444. VertexBuffer._TangentKind = "tangent";
  23445. VertexBuffer._UVKind = "uv";
  23446. VertexBuffer._UV2Kind = "uv2";
  23447. VertexBuffer._UV3Kind = "uv3";
  23448. VertexBuffer._UV4Kind = "uv4";
  23449. VertexBuffer._UV5Kind = "uv5";
  23450. VertexBuffer._UV6Kind = "uv6";
  23451. VertexBuffer._ColorKind = "color";
  23452. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23453. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23454. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23455. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23456. return VertexBuffer;
  23457. }());
  23458. BABYLON.VertexBuffer = VertexBuffer;
  23459. })(BABYLON || (BABYLON = {}));
  23460. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23461. var BABYLON;
  23462. (function (BABYLON) {
  23463. var InternalTexture = /** @class */ (function () {
  23464. function InternalTexture(engine, dataSource) {
  23465. this.onLoadedObservable = new BABYLON.Observable();
  23466. // Private
  23467. this._initialSlot = -1;
  23468. this._designatedSlot = -1;
  23469. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23470. this._references = 1;
  23471. this._engine = engine;
  23472. this._dataSource = dataSource;
  23473. this._webGLTexture = engine._createTexture();
  23474. }
  23475. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23476. get: function () {
  23477. return this._dataSource;
  23478. },
  23479. enumerable: true,
  23480. configurable: true
  23481. });
  23482. InternalTexture.prototype.incrementReferences = function () {
  23483. this._references++;
  23484. };
  23485. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23486. if (depth === void 0) { depth = 1; }
  23487. this.width = width;
  23488. this.height = height;
  23489. this.depth = depth;
  23490. this.baseWidth = width;
  23491. this.baseHeight = height;
  23492. this.baseDepth = depth;
  23493. this._size = width * height * depth;
  23494. };
  23495. InternalTexture.prototype._rebuild = function () {
  23496. var _this = this;
  23497. var proxy;
  23498. this.isReady = false;
  23499. this._cachedCoordinatesMode = null;
  23500. this._cachedWrapU = null;
  23501. this._cachedWrapV = null;
  23502. this._cachedAnisotropicFilteringLevel = null;
  23503. switch (this._dataSource) {
  23504. case InternalTexture.DATASOURCE_TEMP:
  23505. return;
  23506. case InternalTexture.DATASOURCE_URL:
  23507. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23508. _this.isReady = true;
  23509. }, null, this._buffer, undefined, this.format);
  23510. proxy._swapAndDie(this);
  23511. return;
  23512. case InternalTexture.DATASOURCE_RAW:
  23513. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23514. proxy._swapAndDie(this);
  23515. this.isReady = true;
  23516. return;
  23517. case InternalTexture.DATASOURCE_RAW3D:
  23518. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23519. proxy._swapAndDie(this);
  23520. this.isReady = true;
  23521. return;
  23522. case InternalTexture.DATASOURCE_DYNAMIC:
  23523. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23524. proxy._swapAndDie(this);
  23525. // The engine will make sure to update content so no need to flag it as isReady = true
  23526. return;
  23527. case InternalTexture.DATASOURCE_RENDERTARGET:
  23528. var options = new BABYLON.RenderTargetCreationOptions();
  23529. options.generateDepthBuffer = this._generateDepthBuffer;
  23530. options.generateMipMaps = this.generateMipMaps;
  23531. options.generateStencilBuffer = this._generateStencilBuffer;
  23532. options.samplingMode = this.samplingMode;
  23533. options.type = this.type;
  23534. if (this.isCube) {
  23535. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23536. }
  23537. else {
  23538. var size = {
  23539. width: this.width,
  23540. height: this.height
  23541. };
  23542. proxy = this._engine.createRenderTargetTexture(size, options);
  23543. }
  23544. proxy._swapAndDie(this);
  23545. this.isReady = true;
  23546. return;
  23547. case InternalTexture.DATASOURCE_CUBE:
  23548. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23549. _this.isReady = true;
  23550. }, null, this.format, this._extension);
  23551. proxy._swapAndDie(this);
  23552. return;
  23553. case InternalTexture.DATASOURCE_CUBERAW:
  23554. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23555. proxy._swapAndDie(this);
  23556. this.isReady = true;
  23557. return;
  23558. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23559. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23560. if (proxy) {
  23561. proxy._swapAndDie(_this);
  23562. }
  23563. _this.isReady = true;
  23564. }, null, this.format, this._extension);
  23565. return;
  23566. }
  23567. };
  23568. InternalTexture.prototype._swapAndDie = function (target) {
  23569. target._webGLTexture = this._webGLTexture;
  23570. if (this._framebuffer) {
  23571. target._framebuffer = this._framebuffer;
  23572. }
  23573. if (this._depthStencilBuffer) {
  23574. target._depthStencilBuffer = this._depthStencilBuffer;
  23575. }
  23576. if (this._lodTextureHigh) {
  23577. if (target._lodTextureHigh) {
  23578. target._lodTextureHigh.dispose();
  23579. }
  23580. target._lodTextureHigh = this._lodTextureHigh;
  23581. }
  23582. if (this._lodTextureMid) {
  23583. if (target._lodTextureMid) {
  23584. target._lodTextureMid.dispose();
  23585. }
  23586. target._lodTextureMid = this._lodTextureMid;
  23587. }
  23588. if (this._lodTextureLow) {
  23589. if (target._lodTextureLow) {
  23590. target._lodTextureLow.dispose();
  23591. }
  23592. target._lodTextureLow = this._lodTextureLow;
  23593. }
  23594. var cache = this._engine.getLoadedTexturesCache();
  23595. var index = cache.indexOf(this);
  23596. if (index !== -1) {
  23597. cache.splice(index, 1);
  23598. }
  23599. };
  23600. InternalTexture.prototype.dispose = function () {
  23601. if (!this._webGLTexture) {
  23602. return;
  23603. }
  23604. this._references--;
  23605. if (this._references === 0) {
  23606. this._engine._releaseTexture(this);
  23607. this._webGLTexture = null;
  23608. }
  23609. };
  23610. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23611. InternalTexture.DATASOURCE_URL = 1;
  23612. InternalTexture.DATASOURCE_TEMP = 2;
  23613. InternalTexture.DATASOURCE_RAW = 3;
  23614. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23615. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23616. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23617. InternalTexture.DATASOURCE_CUBE = 7;
  23618. InternalTexture.DATASOURCE_CUBERAW = 8;
  23619. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23620. InternalTexture.DATASOURCE_RAW3D = 10;
  23621. return InternalTexture;
  23622. }());
  23623. BABYLON.InternalTexture = InternalTexture;
  23624. })(BABYLON || (BABYLON = {}));
  23625. //# sourceMappingURL=babylon.internalTexture.js.map
  23626. var BABYLON;
  23627. (function (BABYLON) {
  23628. var BaseTexture = /** @class */ (function () {
  23629. function BaseTexture(scene) {
  23630. this._hasAlpha = false;
  23631. this.getAlphaFromRGB = false;
  23632. this.level = 1;
  23633. this.coordinatesIndex = 0;
  23634. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23635. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23636. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23637. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23638. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23639. this.isCube = false;
  23640. this.is3D = false;
  23641. this.gammaSpace = true;
  23642. this.invertZ = false;
  23643. this.lodLevelInAlpha = false;
  23644. this.lodGenerationOffset = 0.0;
  23645. this.lodGenerationScale = 0.8;
  23646. this.isRenderTarget = false;
  23647. this.animations = new Array();
  23648. /**
  23649. * An event triggered when the texture is disposed.
  23650. * @type {BABYLON.Observable}
  23651. */
  23652. this.onDisposeObservable = new BABYLON.Observable();
  23653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23654. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23655. if (this._scene) {
  23656. this._scene.textures.push(this);
  23657. }
  23658. this._uid = null;
  23659. }
  23660. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23661. get: function () {
  23662. return this._hasAlpha;
  23663. },
  23664. set: function (value) {
  23665. if (this._hasAlpha === value) {
  23666. return;
  23667. }
  23668. this._hasAlpha = value;
  23669. if (this._scene) {
  23670. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23671. }
  23672. },
  23673. enumerable: true,
  23674. configurable: true
  23675. });
  23676. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23677. get: function () {
  23678. return this._coordinatesMode;
  23679. },
  23680. set: function (value) {
  23681. if (this._coordinatesMode === value) {
  23682. return;
  23683. }
  23684. this._coordinatesMode = value;
  23685. if (this._scene) {
  23686. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23687. }
  23688. },
  23689. enumerable: true,
  23690. configurable: true
  23691. });
  23692. Object.defineProperty(BaseTexture.prototype, "uid", {
  23693. get: function () {
  23694. if (!this._uid) {
  23695. this._uid = BABYLON.Tools.RandomId();
  23696. }
  23697. return this._uid;
  23698. },
  23699. enumerable: true,
  23700. configurable: true
  23701. });
  23702. BaseTexture.prototype.toString = function () {
  23703. return this.name;
  23704. };
  23705. BaseTexture.prototype.getClassName = function () {
  23706. return "BaseTexture";
  23707. };
  23708. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23709. set: function (callback) {
  23710. if (this._onDisposeObserver) {
  23711. this.onDisposeObservable.remove(this._onDisposeObserver);
  23712. }
  23713. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23714. },
  23715. enumerable: true,
  23716. configurable: true
  23717. });
  23718. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23719. get: function () {
  23720. return true;
  23721. },
  23722. enumerable: true,
  23723. configurable: true
  23724. });
  23725. BaseTexture.prototype.getScene = function () {
  23726. return this._scene;
  23727. };
  23728. BaseTexture.prototype.getTextureMatrix = function () {
  23729. return BABYLON.Matrix.IdentityReadOnly;
  23730. };
  23731. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23732. return BABYLON.Matrix.IdentityReadOnly;
  23733. };
  23734. BaseTexture.prototype.getInternalTexture = function () {
  23735. return this._texture;
  23736. };
  23737. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23738. return !this.isBlocking || this.isReady();
  23739. };
  23740. BaseTexture.prototype.isReady = function () {
  23741. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23742. this.delayLoad();
  23743. return false;
  23744. }
  23745. if (this._texture) {
  23746. return this._texture.isReady;
  23747. }
  23748. return false;
  23749. };
  23750. BaseTexture.prototype.getSize = function () {
  23751. if (this._texture && this._texture.width) {
  23752. return new BABYLON.Size(this._texture.width, this._texture.height);
  23753. }
  23754. if (this._texture && this._texture._size) {
  23755. return new BABYLON.Size(this._texture._size, this._texture._size);
  23756. }
  23757. return BABYLON.Size.Zero();
  23758. };
  23759. BaseTexture.prototype.getBaseSize = function () {
  23760. if (!this.isReady() || !this._texture)
  23761. return BABYLON.Size.Zero();
  23762. if (this._texture._size) {
  23763. return new BABYLON.Size(this._texture._size, this._texture._size);
  23764. }
  23765. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23766. };
  23767. BaseTexture.prototype.scale = function (ratio) {
  23768. };
  23769. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23770. get: function () {
  23771. return false;
  23772. },
  23773. enumerable: true,
  23774. configurable: true
  23775. });
  23776. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23777. if (!this._scene) {
  23778. return null;
  23779. }
  23780. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23781. for (var index = 0; index < texturesCache.length; index++) {
  23782. var texturesCacheEntry = texturesCache[index];
  23783. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23784. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23785. texturesCacheEntry.incrementReferences();
  23786. return texturesCacheEntry;
  23787. }
  23788. }
  23789. }
  23790. return null;
  23791. };
  23792. BaseTexture.prototype._rebuild = function () {
  23793. };
  23794. BaseTexture.prototype.delayLoad = function () {
  23795. };
  23796. BaseTexture.prototype.clone = function () {
  23797. return null;
  23798. };
  23799. Object.defineProperty(BaseTexture.prototype, "textureType", {
  23800. get: function () {
  23801. if (!this._texture) {
  23802. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23803. }
  23804. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23805. },
  23806. enumerable: true,
  23807. configurable: true
  23808. });
  23809. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  23810. get: function () {
  23811. if (!this._texture) {
  23812. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23813. }
  23814. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23815. },
  23816. enumerable: true,
  23817. configurable: true
  23818. });
  23819. BaseTexture.prototype.readPixels = function (faceIndex) {
  23820. if (faceIndex === void 0) { faceIndex = 0; }
  23821. if (!this._texture) {
  23822. return null;
  23823. }
  23824. var size = this.getSize();
  23825. var scene = this.getScene();
  23826. if (!scene) {
  23827. return null;
  23828. }
  23829. var engine = scene.getEngine();
  23830. if (this._texture.isCube) {
  23831. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  23832. }
  23833. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  23834. };
  23835. BaseTexture.prototype.releaseInternalTexture = function () {
  23836. if (this._texture) {
  23837. this._texture.dispose();
  23838. this._texture = null;
  23839. }
  23840. };
  23841. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  23842. get: function () {
  23843. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  23844. return null;
  23845. }
  23846. if (!this._texture._sphericalPolynomial) {
  23847. this._texture._sphericalPolynomial =
  23848. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  23849. }
  23850. return this._texture._sphericalPolynomial;
  23851. },
  23852. set: function (value) {
  23853. if (this._texture) {
  23854. this._texture._sphericalPolynomial = value;
  23855. }
  23856. },
  23857. enumerable: true,
  23858. configurable: true
  23859. });
  23860. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  23861. get: function () {
  23862. if (this._texture) {
  23863. return this._texture._lodTextureHigh;
  23864. }
  23865. return null;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  23871. get: function () {
  23872. if (this._texture) {
  23873. return this._texture._lodTextureMid;
  23874. }
  23875. return null;
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  23881. get: function () {
  23882. if (this._texture) {
  23883. return this._texture._lodTextureLow;
  23884. }
  23885. return null;
  23886. },
  23887. enumerable: true,
  23888. configurable: true
  23889. });
  23890. BaseTexture.prototype.dispose = function () {
  23891. if (!this._scene) {
  23892. return;
  23893. }
  23894. // Animations
  23895. this._scene.stopAnimation(this);
  23896. // Remove from scene
  23897. this._scene._removePendingData(this);
  23898. var index = this._scene.textures.indexOf(this);
  23899. if (index >= 0) {
  23900. this._scene.textures.splice(index, 1);
  23901. }
  23902. if (this._texture === undefined) {
  23903. return;
  23904. }
  23905. // Release
  23906. this.releaseInternalTexture();
  23907. // Callback
  23908. this.onDisposeObservable.notifyObservers(this);
  23909. this.onDisposeObservable.clear();
  23910. };
  23911. BaseTexture.prototype.serialize = function () {
  23912. if (!this.name) {
  23913. return null;
  23914. }
  23915. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23916. // Animations
  23917. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23918. return serializationObject;
  23919. };
  23920. BaseTexture.WhenAllReady = function (textures, callback) {
  23921. var numRemaining = textures.length;
  23922. if (numRemaining === 0) {
  23923. callback();
  23924. return;
  23925. }
  23926. var _loop_1 = function () {
  23927. texture = textures[i];
  23928. if (texture.isReady()) {
  23929. if (--numRemaining === 0) {
  23930. callback();
  23931. }
  23932. }
  23933. else {
  23934. onLoadObservable = texture.onLoadObservable;
  23935. var onLoadCallback_1 = function () {
  23936. onLoadObservable.removeCallback(onLoadCallback_1);
  23937. if (--numRemaining === 0) {
  23938. callback();
  23939. }
  23940. };
  23941. onLoadObservable.add(onLoadCallback_1);
  23942. }
  23943. };
  23944. var texture, onLoadObservable;
  23945. for (var i = 0; i < textures.length; i++) {
  23946. _loop_1();
  23947. }
  23948. };
  23949. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  23950. __decorate([
  23951. BABYLON.serialize()
  23952. ], BaseTexture.prototype, "name", void 0);
  23953. __decorate([
  23954. BABYLON.serialize("hasAlpha")
  23955. ], BaseTexture.prototype, "_hasAlpha", void 0);
  23956. __decorate([
  23957. BABYLON.serialize()
  23958. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23959. __decorate([
  23960. BABYLON.serialize()
  23961. ], BaseTexture.prototype, "level", void 0);
  23962. __decorate([
  23963. BABYLON.serialize()
  23964. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23965. __decorate([
  23966. BABYLON.serialize("coordinatesMode")
  23967. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23968. __decorate([
  23969. BABYLON.serialize()
  23970. ], BaseTexture.prototype, "wrapU", void 0);
  23971. __decorate([
  23972. BABYLON.serialize()
  23973. ], BaseTexture.prototype, "wrapV", void 0);
  23974. __decorate([
  23975. BABYLON.serialize()
  23976. ], BaseTexture.prototype, "wrapR", void 0);
  23977. __decorate([
  23978. BABYLON.serialize()
  23979. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23980. __decorate([
  23981. BABYLON.serialize()
  23982. ], BaseTexture.prototype, "isCube", void 0);
  23983. __decorate([
  23984. BABYLON.serialize()
  23985. ], BaseTexture.prototype, "is3D", void 0);
  23986. __decorate([
  23987. BABYLON.serialize()
  23988. ], BaseTexture.prototype, "gammaSpace", void 0);
  23989. __decorate([
  23990. BABYLON.serialize()
  23991. ], BaseTexture.prototype, "invertZ", void 0);
  23992. __decorate([
  23993. BABYLON.serialize()
  23994. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  23995. __decorate([
  23996. BABYLON.serialize()
  23997. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  23998. __decorate([
  23999. BABYLON.serialize()
  24000. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24001. __decorate([
  24002. BABYLON.serialize()
  24003. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24004. return BaseTexture;
  24005. }());
  24006. BABYLON.BaseTexture = BaseTexture;
  24007. })(BABYLON || (BABYLON = {}));
  24008. //# sourceMappingURL=babylon.baseTexture.js.map
  24009. var BABYLON;
  24010. (function (BABYLON) {
  24011. var Texture = /** @class */ (function (_super) {
  24012. __extends(Texture, _super);
  24013. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24014. if (noMipmap === void 0) { noMipmap = false; }
  24015. if (invertY === void 0) { invertY = true; }
  24016. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24017. if (onLoad === void 0) { onLoad = null; }
  24018. if (onError === void 0) { onError = null; }
  24019. if (buffer === void 0) { buffer = null; }
  24020. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24021. var _this = _super.call(this, scene) || this;
  24022. _this.uOffset = 0;
  24023. _this.vOffset = 0;
  24024. _this.uScale = 1.0;
  24025. _this.vScale = 1.0;
  24026. _this.uAng = 0;
  24027. _this.vAng = 0;
  24028. _this.wAng = 0;
  24029. _this._isBlocking = true;
  24030. _this.name = url || "";
  24031. _this.url = url;
  24032. _this._noMipmap = noMipmap;
  24033. _this._invertY = invertY;
  24034. _this._samplingMode = samplingMode;
  24035. _this._buffer = buffer;
  24036. _this._deleteBuffer = deleteBuffer;
  24037. if (format) {
  24038. _this._format = format;
  24039. }
  24040. scene = _this.getScene();
  24041. if (!scene) {
  24042. return _this;
  24043. }
  24044. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24045. var load = function () {
  24046. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24047. _this.onLoadObservable.notifyObservers(_this);
  24048. }
  24049. if (onLoad) {
  24050. onLoad();
  24051. }
  24052. if (!_this.isBlocking && scene) {
  24053. scene.resetCachedMaterial();
  24054. }
  24055. };
  24056. if (!_this.url) {
  24057. _this._delayedOnLoad = load;
  24058. _this._delayedOnError = onError;
  24059. return _this;
  24060. }
  24061. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24062. if (!_this._texture) {
  24063. if (!scene.useDelayedTextureLoading) {
  24064. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24065. if (deleteBuffer) {
  24066. delete _this._buffer;
  24067. }
  24068. }
  24069. else {
  24070. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24071. _this._delayedOnLoad = load;
  24072. _this._delayedOnError = onError;
  24073. }
  24074. }
  24075. else {
  24076. if (_this._texture.isReady) {
  24077. BABYLON.Tools.SetImmediate(function () { return load(); });
  24078. }
  24079. else {
  24080. _this._texture.onLoadedObservable.add(load);
  24081. }
  24082. }
  24083. return _this;
  24084. }
  24085. Object.defineProperty(Texture.prototype, "noMipmap", {
  24086. get: function () {
  24087. return this._noMipmap;
  24088. },
  24089. enumerable: true,
  24090. configurable: true
  24091. });
  24092. Object.defineProperty(Texture.prototype, "isBlocking", {
  24093. get: function () {
  24094. return this._isBlocking;
  24095. },
  24096. set: function (value) {
  24097. this._isBlocking = value;
  24098. },
  24099. enumerable: true,
  24100. configurable: true
  24101. });
  24102. Object.defineProperty(Texture.prototype, "samplingMode", {
  24103. get: function () {
  24104. return this._samplingMode;
  24105. },
  24106. enumerable: true,
  24107. configurable: true
  24108. });
  24109. Texture.prototype.updateURL = function (url) {
  24110. this.url = url;
  24111. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24112. this.delayLoad();
  24113. };
  24114. Texture.prototype.delayLoad = function () {
  24115. var _this = this;
  24116. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24117. return;
  24118. }
  24119. var scene = this.getScene();
  24120. if (!scene) {
  24121. return;
  24122. }
  24123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24124. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24125. if (!this._texture) {
  24126. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24127. if (this._deleteBuffer) {
  24128. delete this._buffer;
  24129. }
  24130. }
  24131. else {
  24132. if (this._texture.isReady) {
  24133. BABYLON.Tools.SetImmediate(function () {
  24134. if (!_this._delayedOnLoad) {
  24135. return;
  24136. }
  24137. _this._delayedOnLoad();
  24138. });
  24139. }
  24140. else {
  24141. if (this._delayedOnLoad) {
  24142. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24143. }
  24144. }
  24145. }
  24146. };
  24147. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24148. if (!this._texture) {
  24149. return;
  24150. }
  24151. var scene = this.getScene();
  24152. if (!scene) {
  24153. return;
  24154. }
  24155. this._samplingMode = samplingMode;
  24156. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24157. };
  24158. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24159. x *= this.uScale;
  24160. y *= this.vScale;
  24161. x -= 0.5 * this.uScale;
  24162. y -= 0.5 * this.vScale;
  24163. z -= 0.5;
  24164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24165. t.x += 0.5 * this.uScale + this.uOffset;
  24166. t.y += 0.5 * this.vScale + this.vOffset;
  24167. t.z += 0.5;
  24168. };
  24169. Texture.prototype.getTextureMatrix = function () {
  24170. var _this = this;
  24171. if (this.uOffset === this._cachedUOffset &&
  24172. this.vOffset === this._cachedVOffset &&
  24173. this.uScale === this._cachedUScale &&
  24174. this.vScale === this._cachedVScale &&
  24175. this.uAng === this._cachedUAng &&
  24176. this.vAng === this._cachedVAng &&
  24177. this.wAng === this._cachedWAng) {
  24178. return this._cachedTextureMatrix;
  24179. }
  24180. this._cachedUOffset = this.uOffset;
  24181. this._cachedVOffset = this.vOffset;
  24182. this._cachedUScale = this.uScale;
  24183. this._cachedVScale = this.vScale;
  24184. this._cachedUAng = this.uAng;
  24185. this._cachedVAng = this.vAng;
  24186. this._cachedWAng = this.wAng;
  24187. if (!this._cachedTextureMatrix) {
  24188. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24189. this._rowGenerationMatrix = new BABYLON.Matrix();
  24190. this._t0 = BABYLON.Vector3.Zero();
  24191. this._t1 = BABYLON.Vector3.Zero();
  24192. this._t2 = BABYLON.Vector3.Zero();
  24193. }
  24194. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24195. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24196. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24197. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24198. this._t1.subtractInPlace(this._t0);
  24199. this._t2.subtractInPlace(this._t0);
  24200. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24201. this._cachedTextureMatrix.m[0] = this._t1.x;
  24202. this._cachedTextureMatrix.m[1] = this._t1.y;
  24203. this._cachedTextureMatrix.m[2] = this._t1.z;
  24204. this._cachedTextureMatrix.m[4] = this._t2.x;
  24205. this._cachedTextureMatrix.m[5] = this._t2.y;
  24206. this._cachedTextureMatrix.m[6] = this._t2.z;
  24207. this._cachedTextureMatrix.m[8] = this._t0.x;
  24208. this._cachedTextureMatrix.m[9] = this._t0.y;
  24209. this._cachedTextureMatrix.m[10] = this._t0.z;
  24210. var scene = this.getScene();
  24211. if (!scene) {
  24212. return this._cachedTextureMatrix;
  24213. }
  24214. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24215. return mat.hasTexture(_this);
  24216. });
  24217. return this._cachedTextureMatrix;
  24218. };
  24219. Texture.prototype.getReflectionTextureMatrix = function () {
  24220. var _this = this;
  24221. var scene = this.getScene();
  24222. if (!scene) {
  24223. return this._cachedTextureMatrix;
  24224. }
  24225. if (this.uOffset === this._cachedUOffset &&
  24226. this.vOffset === this._cachedVOffset &&
  24227. this.uScale === this._cachedUScale &&
  24228. this.vScale === this._cachedVScale &&
  24229. this.coordinatesMode === this._cachedCoordinatesMode) {
  24230. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24231. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24232. return this._cachedTextureMatrix;
  24233. }
  24234. }
  24235. else {
  24236. return this._cachedTextureMatrix;
  24237. }
  24238. }
  24239. if (!this._cachedTextureMatrix) {
  24240. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24241. }
  24242. if (!this._projectionModeMatrix) {
  24243. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24244. }
  24245. this._cachedUOffset = this.uOffset;
  24246. this._cachedVOffset = this.vOffset;
  24247. this._cachedUScale = this.uScale;
  24248. this._cachedVScale = this.vScale;
  24249. this._cachedCoordinatesMode = this.coordinatesMode;
  24250. switch (this.coordinatesMode) {
  24251. case Texture.PLANAR_MODE:
  24252. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24253. this._cachedTextureMatrix[0] = this.uScale;
  24254. this._cachedTextureMatrix[5] = this.vScale;
  24255. this._cachedTextureMatrix[12] = this.uOffset;
  24256. this._cachedTextureMatrix[13] = this.vOffset;
  24257. break;
  24258. case Texture.PROJECTION_MODE:
  24259. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24260. this._projectionModeMatrix.m[0] = 0.5;
  24261. this._projectionModeMatrix.m[5] = -0.5;
  24262. this._projectionModeMatrix.m[10] = 0.0;
  24263. this._projectionModeMatrix.m[12] = 0.5;
  24264. this._projectionModeMatrix.m[13] = 0.5;
  24265. this._projectionModeMatrix.m[14] = 1.0;
  24266. this._projectionModeMatrix.m[15] = 1.0;
  24267. var projectionMatrix = scene.getProjectionMatrix();
  24268. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24269. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24270. break;
  24271. default:
  24272. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24273. break;
  24274. }
  24275. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24276. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24277. });
  24278. return this._cachedTextureMatrix;
  24279. };
  24280. Texture.prototype.clone = function () {
  24281. var _this = this;
  24282. return BABYLON.SerializationHelper.Clone(function () {
  24283. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24284. }, this);
  24285. };
  24286. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24287. get: function () {
  24288. if (!this._onLoadObservable) {
  24289. this._onLoadObservable = new BABYLON.Observable();
  24290. }
  24291. return this._onLoadObservable;
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. Texture.prototype.serialize = function () {
  24297. var serializationObject = _super.prototype.serialize.call(this);
  24298. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24299. serializationObject.base64String = this._buffer;
  24300. serializationObject.name = serializationObject.name.replace("data:", "");
  24301. }
  24302. return serializationObject;
  24303. };
  24304. Texture.prototype.getClassName = function () {
  24305. return "Texture";
  24306. };
  24307. Texture.prototype.dispose = function () {
  24308. _super.prototype.dispose.call(this);
  24309. if (this.onLoadObservable) {
  24310. this.onLoadObservable.clear();
  24311. this._onLoadObservable = null;
  24312. }
  24313. this._delayedOnLoad = null;
  24314. this._delayedOnError = null;
  24315. };
  24316. // Statics
  24317. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24318. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24319. if (onLoad === void 0) { onLoad = null; }
  24320. if (onError === void 0) { onError = null; }
  24321. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24322. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24323. };
  24324. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24325. if (parsedTexture.customType) {
  24326. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24327. // Update Sampling Mode
  24328. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24329. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24330. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24331. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24332. }
  24333. }
  24334. return parsedCustomTexture;
  24335. }
  24336. if (parsedTexture.isCube) {
  24337. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24338. }
  24339. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24340. return null;
  24341. }
  24342. var texture = BABYLON.SerializationHelper.Parse(function () {
  24343. var generateMipMaps = true;
  24344. if (parsedTexture.noMipmap) {
  24345. generateMipMaps = false;
  24346. }
  24347. if (parsedTexture.mirrorPlane) {
  24348. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24349. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24350. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24351. return mirrorTexture;
  24352. }
  24353. else if (parsedTexture.isRenderTarget) {
  24354. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24355. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24356. return renderTargetTexture;
  24357. }
  24358. else {
  24359. var texture;
  24360. if (parsedTexture.base64String) {
  24361. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24362. }
  24363. else {
  24364. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24365. }
  24366. return texture;
  24367. }
  24368. }, parsedTexture, scene);
  24369. // Update Sampling Mode
  24370. if (parsedTexture.samplingMode) {
  24371. var sampling = parsedTexture.samplingMode;
  24372. if (texture._samplingMode !== sampling) {
  24373. texture.updateSamplingMode(sampling);
  24374. }
  24375. }
  24376. // Animations
  24377. if (parsedTexture.animations) {
  24378. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24379. var parsedAnimation = parsedTexture.animations[animationIndex];
  24380. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24381. }
  24382. }
  24383. return texture;
  24384. };
  24385. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24386. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24387. if (noMipmap === void 0) { noMipmap = false; }
  24388. if (invertY === void 0) { invertY = true; }
  24389. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24390. if (onLoad === void 0) { onLoad = null; }
  24391. if (onError === void 0) { onError = null; }
  24392. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24393. if (name.substr(0, 5) !== "data:") {
  24394. name = "data:" + name;
  24395. }
  24396. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24397. };
  24398. // Constants
  24399. Texture.NEAREST_SAMPLINGMODE = 1;
  24400. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24401. Texture.BILINEAR_SAMPLINGMODE = 2;
  24402. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24403. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24404. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24405. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24406. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24407. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24408. Texture.NEAREST_LINEAR = 7;
  24409. Texture.NEAREST_NEAREST = 8;
  24410. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24411. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24412. Texture.LINEAR_LINEAR = 11;
  24413. Texture.LINEAR_NEAREST = 12;
  24414. Texture.EXPLICIT_MODE = 0;
  24415. Texture.SPHERICAL_MODE = 1;
  24416. Texture.PLANAR_MODE = 2;
  24417. Texture.CUBIC_MODE = 3;
  24418. Texture.PROJECTION_MODE = 4;
  24419. Texture.SKYBOX_MODE = 5;
  24420. Texture.INVCUBIC_MODE = 6;
  24421. Texture.EQUIRECTANGULAR_MODE = 7;
  24422. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24423. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24424. Texture.CLAMP_ADDRESSMODE = 0;
  24425. Texture.WRAP_ADDRESSMODE = 1;
  24426. Texture.MIRROR_ADDRESSMODE = 2;
  24427. __decorate([
  24428. BABYLON.serialize()
  24429. ], Texture.prototype, "url", void 0);
  24430. __decorate([
  24431. BABYLON.serialize()
  24432. ], Texture.prototype, "uOffset", void 0);
  24433. __decorate([
  24434. BABYLON.serialize()
  24435. ], Texture.prototype, "vOffset", void 0);
  24436. __decorate([
  24437. BABYLON.serialize()
  24438. ], Texture.prototype, "uScale", void 0);
  24439. __decorate([
  24440. BABYLON.serialize()
  24441. ], Texture.prototype, "vScale", void 0);
  24442. __decorate([
  24443. BABYLON.serialize()
  24444. ], Texture.prototype, "uAng", void 0);
  24445. __decorate([
  24446. BABYLON.serialize()
  24447. ], Texture.prototype, "vAng", void 0);
  24448. __decorate([
  24449. BABYLON.serialize()
  24450. ], Texture.prototype, "wAng", void 0);
  24451. __decorate([
  24452. BABYLON.serialize()
  24453. ], Texture.prototype, "isBlocking", null);
  24454. return Texture;
  24455. }(BABYLON.BaseTexture));
  24456. BABYLON.Texture = Texture;
  24457. })(BABYLON || (BABYLON = {}));
  24458. //# sourceMappingURL=babylon.texture.js.map
  24459. var BABYLON;
  24460. (function (BABYLON) {
  24461. var _InstancesBatch = /** @class */ (function () {
  24462. function _InstancesBatch() {
  24463. this.mustReturn = false;
  24464. this.visibleInstances = new Array();
  24465. this.renderSelf = new Array();
  24466. }
  24467. return _InstancesBatch;
  24468. }());
  24469. BABYLON._InstancesBatch = _InstancesBatch;
  24470. var Mesh = /** @class */ (function (_super) {
  24471. __extends(Mesh, _super);
  24472. /**
  24473. * @constructor
  24474. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24475. * @param {Scene} scene The scene to add this mesh to.
  24476. * @param {Node} parent The parent of this mesh, if it has one
  24477. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24478. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24479. * When false, achieved by calling a clone(), also passing False.
  24480. * This will make creation of children, recursive.
  24481. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24482. */
  24483. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24484. if (scene === void 0) { scene = null; }
  24485. if (parent === void 0) { parent = null; }
  24486. if (source === void 0) { source = null; }
  24487. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24488. var _this = _super.call(this, name, scene) || this;
  24489. // Events
  24490. /**
  24491. * An event triggered before rendering the mesh
  24492. * @type {BABYLON.Observable}
  24493. */
  24494. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24495. /**
  24496. * An event triggered after rendering the mesh
  24497. * @type {BABYLON.Observable}
  24498. */
  24499. _this.onAfterRenderObservable = new BABYLON.Observable();
  24500. /**
  24501. * An event triggered before drawing the mesh
  24502. * @type {BABYLON.Observable}
  24503. */
  24504. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24505. // Members
  24506. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24507. _this.instances = new Array();
  24508. _this._LODLevels = new Array();
  24509. _this._visibleInstances = {};
  24510. _this._renderIdForInstances = new Array();
  24511. _this._batchCache = new _InstancesBatch();
  24512. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24513. // Use by builder only to know what orientation were the mesh build in.
  24514. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24515. _this.overrideMaterialSideOrientation = null;
  24516. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24517. // Will be used to save a source mesh reference, If any
  24518. _this._source = null;
  24519. scene = _this.getScene();
  24520. if (source) {
  24521. // Source mesh
  24522. _this._source = source;
  24523. // Geometry
  24524. if (source._geometry) {
  24525. source._geometry.applyToMesh(_this);
  24526. }
  24527. // Deep copy
  24528. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24529. // Metadata
  24530. if (source.metadata && source.metadata.clone) {
  24531. _this.metadata = source.metadata.clone();
  24532. }
  24533. else {
  24534. _this.metadata = source.metadata;
  24535. }
  24536. // Tags
  24537. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24538. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24539. }
  24540. // Parent
  24541. _this.parent = source.parent;
  24542. // Pivot
  24543. _this.setPivotMatrix(source.getPivotMatrix());
  24544. _this.id = name + "." + source.id;
  24545. // Material
  24546. _this.material = source.material;
  24547. var index;
  24548. if (!doNotCloneChildren) {
  24549. // Children
  24550. var directDescendants = source.getDescendants(true);
  24551. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24552. var child = directDescendants[index_1];
  24553. if (child.clone) {
  24554. child.clone(name + "." + child.name, _this);
  24555. }
  24556. }
  24557. }
  24558. // Physics clone
  24559. var physicsEngine = _this.getScene().getPhysicsEngine();
  24560. if (clonePhysicsImpostor && physicsEngine) {
  24561. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24562. if (impostor) {
  24563. _this.physicsImpostor = impostor.clone(_this);
  24564. }
  24565. }
  24566. // Particles
  24567. for (index = 0; index < scene.particleSystems.length; index++) {
  24568. var system = scene.particleSystems[index];
  24569. if (system.emitter === source) {
  24570. system.clone(system.name, _this);
  24571. }
  24572. }
  24573. _this.computeWorldMatrix(true);
  24574. }
  24575. // Parent
  24576. if (parent !== null) {
  24577. _this.parent = parent;
  24578. }
  24579. return _this;
  24580. }
  24581. Object.defineProperty(Mesh, "FRONTSIDE", {
  24582. /**
  24583. * Mesh side orientation : usually the external or front surface
  24584. */
  24585. get: function () {
  24586. return Mesh._FRONTSIDE;
  24587. },
  24588. enumerable: true,
  24589. configurable: true
  24590. });
  24591. Object.defineProperty(Mesh, "BACKSIDE", {
  24592. /**
  24593. * Mesh side orientation : usually the internal or back surface
  24594. */
  24595. get: function () {
  24596. return Mesh._BACKSIDE;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24602. /**
  24603. * Mesh side orientation : both internal and external or front and back surfaces
  24604. */
  24605. get: function () {
  24606. return Mesh._DOUBLESIDE;
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24612. /**
  24613. * Mesh side orientation : by default, `FRONTSIDE`
  24614. */
  24615. get: function () {
  24616. return Mesh._DEFAULTSIDE;
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Object.defineProperty(Mesh, "NO_CAP", {
  24622. /**
  24623. * Mesh cap setting : no cap
  24624. */
  24625. get: function () {
  24626. return Mesh._NO_CAP;
  24627. },
  24628. enumerable: true,
  24629. configurable: true
  24630. });
  24631. Object.defineProperty(Mesh, "CAP_START", {
  24632. /**
  24633. * Mesh cap setting : one cap at the beginning of the mesh
  24634. */
  24635. get: function () {
  24636. return Mesh._CAP_START;
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. Object.defineProperty(Mesh, "CAP_END", {
  24642. /**
  24643. * Mesh cap setting : one cap at the end of the mesh
  24644. */
  24645. get: function () {
  24646. return Mesh._CAP_END;
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Mesh, "CAP_ALL", {
  24652. /**
  24653. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24654. */
  24655. get: function () {
  24656. return Mesh._CAP_ALL;
  24657. },
  24658. enumerable: true,
  24659. configurable: true
  24660. });
  24661. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24662. set: function (callback) {
  24663. if (this._onBeforeDrawObserver) {
  24664. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24665. }
  24666. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24672. get: function () {
  24673. return this._morphTargetManager;
  24674. },
  24675. set: function (value) {
  24676. if (this._morphTargetManager === value) {
  24677. return;
  24678. }
  24679. this._morphTargetManager = value;
  24680. this._syncGeometryWithMorphTargetManager();
  24681. },
  24682. enumerable: true,
  24683. configurable: true
  24684. });
  24685. Object.defineProperty(Mesh.prototype, "source", {
  24686. get: function () {
  24687. return this._source;
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24693. get: function () {
  24694. return this._unIndexed;
  24695. },
  24696. set: function (value) {
  24697. if (this._unIndexed !== value) {
  24698. this._unIndexed = value;
  24699. this._markSubMeshesAsAttributesDirty();
  24700. }
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. // Methods
  24706. /**
  24707. * Returns the string "Mesh".
  24708. */
  24709. Mesh.prototype.getClassName = function () {
  24710. return "Mesh";
  24711. };
  24712. /**
  24713. * Returns a string.
  24714. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24715. */
  24716. Mesh.prototype.toString = function (fullDetails) {
  24717. var ret = _super.prototype.toString.call(this, fullDetails);
  24718. ret += ", n vertices: " + this.getTotalVertices();
  24719. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24720. if (this.animations) {
  24721. for (var i = 0; i < this.animations.length; i++) {
  24722. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24723. }
  24724. }
  24725. if (fullDetails) {
  24726. if (this._geometry) {
  24727. var ib = this.getIndices();
  24728. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24729. if (vb && ib) {
  24730. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24731. }
  24732. }
  24733. else {
  24734. ret += ", flat shading: UNKNOWN";
  24735. }
  24736. }
  24737. return ret;
  24738. };
  24739. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24740. /**
  24741. * True if the mesh has some Levels Of Details (LOD).
  24742. * Returns a boolean.
  24743. */
  24744. get: function () {
  24745. return this._LODLevels.length > 0;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. Mesh.prototype._sortLODLevels = function () {
  24751. this._LODLevels.sort(function (a, b) {
  24752. if (a.distance < b.distance) {
  24753. return 1;
  24754. }
  24755. if (a.distance > b.distance) {
  24756. return -1;
  24757. }
  24758. return 0;
  24759. });
  24760. };
  24761. /**
  24762. * Add a mesh as LOD level triggered at the given distance.
  24763. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24764. * @param {number} distance The distance from the center of the object to show this level
  24765. * @param {Mesh} mesh The mesh to be added as LOD level
  24766. * @return {Mesh} This mesh (for chaining)
  24767. */
  24768. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24769. if (mesh && mesh._masterMesh) {
  24770. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24771. return this;
  24772. }
  24773. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24774. this._LODLevels.push(level);
  24775. if (mesh) {
  24776. mesh._masterMesh = this;
  24777. }
  24778. this._sortLODLevels();
  24779. return this;
  24780. };
  24781. /**
  24782. * Returns the LOD level mesh at the passed distance or null if not found.
  24783. * It is related to the method `addLODLevel(distance, mesh)`.
  24784. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24785. * Returns an object Mesh or `null`.
  24786. */
  24787. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24788. for (var index = 0; index < this._LODLevels.length; index++) {
  24789. var level = this._LODLevels[index];
  24790. if (level.distance === distance) {
  24791. return level.mesh;
  24792. }
  24793. }
  24794. return null;
  24795. };
  24796. /**
  24797. * Remove a mesh from the LOD array
  24798. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24799. * @param {Mesh} mesh The mesh to be removed.
  24800. * @return {Mesh} This mesh (for chaining)
  24801. */
  24802. Mesh.prototype.removeLODLevel = function (mesh) {
  24803. for (var index = 0; index < this._LODLevels.length; index++) {
  24804. if (this._LODLevels[index].mesh === mesh) {
  24805. this._LODLevels.splice(index, 1);
  24806. if (mesh) {
  24807. mesh._masterMesh = null;
  24808. }
  24809. }
  24810. }
  24811. this._sortLODLevels();
  24812. return this;
  24813. };
  24814. /**
  24815. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  24816. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24817. */
  24818. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  24819. if (!this._LODLevels || this._LODLevels.length === 0) {
  24820. return this;
  24821. }
  24822. var bSphere;
  24823. if (boundingSphere) {
  24824. bSphere = boundingSphere;
  24825. }
  24826. else {
  24827. var boundingInfo = this.getBoundingInfo();
  24828. bSphere = boundingInfo.boundingSphere;
  24829. }
  24830. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  24831. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  24832. if (this.onLODLevelSelection) {
  24833. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  24834. }
  24835. return this;
  24836. }
  24837. for (var index = 0; index < this._LODLevels.length; index++) {
  24838. var level = this._LODLevels[index];
  24839. if (level.distance < distanceToCamera) {
  24840. if (level.mesh) {
  24841. level.mesh._preActivate();
  24842. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  24843. }
  24844. if (this.onLODLevelSelection) {
  24845. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  24846. }
  24847. return level.mesh;
  24848. }
  24849. }
  24850. if (this.onLODLevelSelection) {
  24851. this.onLODLevelSelection(distanceToCamera, this, this);
  24852. }
  24853. return this;
  24854. };
  24855. Object.defineProperty(Mesh.prototype, "geometry", {
  24856. /**
  24857. * Returns the mesh internal Geometry object.
  24858. */
  24859. get: function () {
  24860. return this._geometry;
  24861. },
  24862. enumerable: true,
  24863. configurable: true
  24864. });
  24865. /**
  24866. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  24867. */
  24868. Mesh.prototype.getTotalVertices = function () {
  24869. if (this._geometry === null || this._geometry === undefined) {
  24870. return 0;
  24871. }
  24872. return this._geometry.getTotalVertices();
  24873. };
  24874. /**
  24875. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  24876. * 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.
  24877. * You can force the copy with forceCopy === true
  24878. * Returns null if the mesh has no geometry or no vertex buffer.
  24879. * Possible `kind` values :
  24880. * - BABYLON.VertexBuffer.PositionKind
  24881. * - BABYLON.VertexBuffer.UVKind
  24882. * - BABYLON.VertexBuffer.UV2Kind
  24883. * - BABYLON.VertexBuffer.UV3Kind
  24884. * - BABYLON.VertexBuffer.UV4Kind
  24885. * - BABYLON.VertexBuffer.UV5Kind
  24886. * - BABYLON.VertexBuffer.UV6Kind
  24887. * - BABYLON.VertexBuffer.ColorKind
  24888. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24889. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24890. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24891. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24892. */
  24893. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  24894. if (!this._geometry) {
  24895. return null;
  24896. }
  24897. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  24898. };
  24899. /**
  24900. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24901. * Returns `null` if the mesh has no geometry.
  24902. * Possible `kind` values :
  24903. * - BABYLON.VertexBuffer.PositionKind
  24904. * - BABYLON.VertexBuffer.UVKind
  24905. * - BABYLON.VertexBuffer.UV2Kind
  24906. * - BABYLON.VertexBuffer.UV3Kind
  24907. * - BABYLON.VertexBuffer.UV4Kind
  24908. * - BABYLON.VertexBuffer.UV5Kind
  24909. * - BABYLON.VertexBuffer.UV6Kind
  24910. * - BABYLON.VertexBuffer.ColorKind
  24911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24915. */
  24916. Mesh.prototype.getVertexBuffer = function (kind) {
  24917. if (!this._geometry) {
  24918. return null;
  24919. }
  24920. return this._geometry.getVertexBuffer(kind);
  24921. };
  24922. /**
  24923. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24924. * Possible `kind` values :
  24925. * - BABYLON.VertexBuffer.PositionKind
  24926. * - BABYLON.VertexBuffer.UVKind
  24927. * - BABYLON.VertexBuffer.UV2Kind
  24928. * - BABYLON.VertexBuffer.UV3Kind
  24929. * - BABYLON.VertexBuffer.UV4Kind
  24930. * - BABYLON.VertexBuffer.UV5Kind
  24931. * - BABYLON.VertexBuffer.UV6Kind
  24932. * - BABYLON.VertexBuffer.ColorKind
  24933. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24934. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24935. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24936. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24937. */
  24938. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24939. if (!this._geometry) {
  24940. if (this._delayInfo) {
  24941. return this._delayInfo.indexOf(kind) !== -1;
  24942. }
  24943. return false;
  24944. }
  24945. return this._geometry.isVerticesDataPresent(kind);
  24946. };
  24947. /**
  24948. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  24949. * Possible `kind` values :
  24950. * - BABYLON.VertexBuffer.PositionKind
  24951. * - BABYLON.VertexBuffer.UVKind
  24952. * - BABYLON.VertexBuffer.UV2Kind
  24953. * - BABYLON.VertexBuffer.UV3Kind
  24954. * - BABYLON.VertexBuffer.UV4Kind
  24955. * - BABYLON.VertexBuffer.UV5Kind
  24956. * - BABYLON.VertexBuffer.UV6Kind
  24957. * - BABYLON.VertexBuffer.ColorKind
  24958. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24959. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24960. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24961. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24962. */
  24963. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24964. if (!this._geometry) {
  24965. if (this._delayInfo) {
  24966. return this._delayInfo.indexOf(kind) !== -1;
  24967. }
  24968. return false;
  24969. }
  24970. return this._geometry.isVertexBufferUpdatable(kind);
  24971. };
  24972. /**
  24973. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24974. * Possible `kind` values :
  24975. * - BABYLON.VertexBuffer.PositionKind
  24976. * - BABYLON.VertexBuffer.UVKind
  24977. * - BABYLON.VertexBuffer.UV2Kind
  24978. * - BABYLON.VertexBuffer.UV3Kind
  24979. * - BABYLON.VertexBuffer.UV4Kind
  24980. * - BABYLON.VertexBuffer.UV5Kind
  24981. * - BABYLON.VertexBuffer.UV6Kind
  24982. * - BABYLON.VertexBuffer.ColorKind
  24983. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24984. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24985. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24986. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24987. */
  24988. Mesh.prototype.getVerticesDataKinds = function () {
  24989. if (!this._geometry) {
  24990. var result = new Array();
  24991. if (this._delayInfo) {
  24992. this._delayInfo.forEach(function (kind, index, array) {
  24993. result.push(kind);
  24994. });
  24995. }
  24996. return result;
  24997. }
  24998. return this._geometry.getVerticesDataKinds();
  24999. };
  25000. /**
  25001. * Returns a positive integer : the total number of indices in this mesh geometry.
  25002. * Returns zero if the mesh has no geometry.
  25003. */
  25004. Mesh.prototype.getTotalIndices = function () {
  25005. if (!this._geometry) {
  25006. return 0;
  25007. }
  25008. return this._geometry.getTotalIndices();
  25009. };
  25010. /**
  25011. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25012. * 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.
  25013. * Returns an empty array if the mesh has no geometry.
  25014. */
  25015. Mesh.prototype.getIndices = function (copyWhenShared) {
  25016. if (!this._geometry) {
  25017. return [];
  25018. }
  25019. return this._geometry.getIndices(copyWhenShared);
  25020. };
  25021. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25022. get: function () {
  25023. return this._masterMesh !== null && this._masterMesh !== undefined;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. /**
  25029. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  25030. */
  25031. Mesh.prototype.isReady = function () {
  25032. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25033. return false;
  25034. }
  25035. return _super.prototype.isReady.call(this);
  25036. };
  25037. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25038. /**
  25039. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25040. * This property is pertinent only for updatable parametric shapes.
  25041. */
  25042. get: function () {
  25043. return this._areNormalsFrozen;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. /**
  25049. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25050. * It has no effect at all on other shapes.
  25051. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25052. * Returns the Mesh.
  25053. */
  25054. Mesh.prototype.freezeNormals = function () {
  25055. this._areNormalsFrozen = true;
  25056. return this;
  25057. };
  25058. /**
  25059. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25060. * It has no effect at all on other shapes.
  25061. * It reactivates the mesh normals computation if it was previously frozen.
  25062. * Returns the Mesh.
  25063. */
  25064. Mesh.prototype.unfreezeNormals = function () {
  25065. this._areNormalsFrozen = false;
  25066. return this;
  25067. };
  25068. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25069. /**
  25070. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25071. */
  25072. set: function (count) {
  25073. this._overridenInstanceCount = count;
  25074. },
  25075. enumerable: true,
  25076. configurable: true
  25077. });
  25078. // Methods
  25079. Mesh.prototype._preActivate = function () {
  25080. var sceneRenderId = this.getScene().getRenderId();
  25081. if (this._preActivateId === sceneRenderId) {
  25082. return this;
  25083. }
  25084. this._preActivateId = sceneRenderId;
  25085. this._visibleInstances = null;
  25086. return this;
  25087. };
  25088. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25089. if (this._visibleInstances) {
  25090. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25091. }
  25092. return this;
  25093. };
  25094. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25095. if (!this._visibleInstances) {
  25096. this._visibleInstances = {};
  25097. this._visibleInstances.defaultRenderId = renderId;
  25098. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25099. }
  25100. if (!this._visibleInstances[renderId]) {
  25101. this._visibleInstances[renderId] = new Array();
  25102. }
  25103. this._visibleInstances[renderId].push(instance);
  25104. return this;
  25105. };
  25106. /**
  25107. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25108. * This means the mesh underlying bounding box and sphere are recomputed.
  25109. * Returns the Mesh.
  25110. */
  25111. Mesh.prototype.refreshBoundingInfo = function () {
  25112. return this._refreshBoundingInfo(false);
  25113. };
  25114. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25115. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25116. return this;
  25117. }
  25118. var data = this._getPositionData(applySkeleton);
  25119. if (data) {
  25120. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25121. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25122. }
  25123. if (this.subMeshes) {
  25124. for (var index = 0; index < this.subMeshes.length; index++) {
  25125. this.subMeshes[index].refreshBoundingInfo();
  25126. }
  25127. }
  25128. this._updateBoundingInfo();
  25129. return this;
  25130. };
  25131. Mesh.prototype._getPositionData = function (applySkeleton) {
  25132. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25133. if (data && applySkeleton && this.skeleton) {
  25134. data = data.slice();
  25135. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25136. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25137. if (matricesWeightsData && matricesIndicesData) {
  25138. var needExtras = this.numBoneInfluencers > 4;
  25139. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25140. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25141. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25142. var tempVector = BABYLON.Tmp.Vector3[0];
  25143. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25144. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25145. var matWeightIdx = 0;
  25146. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25147. finalMatrix.reset();
  25148. var inf;
  25149. var weight;
  25150. for (inf = 0; inf < 4; inf++) {
  25151. weight = matricesWeightsData[matWeightIdx + inf];
  25152. if (weight <= 0)
  25153. break;
  25154. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25155. finalMatrix.addToSelf(tempMatrix);
  25156. }
  25157. if (needExtras) {
  25158. for (inf = 0; inf < 4; inf++) {
  25159. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25160. if (weight <= 0)
  25161. break;
  25162. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25163. finalMatrix.addToSelf(tempMatrix);
  25164. }
  25165. }
  25166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25167. tempVector.toArray(data, index);
  25168. }
  25169. }
  25170. }
  25171. return data;
  25172. };
  25173. Mesh.prototype._createGlobalSubMesh = function (force) {
  25174. var totalVertices = this.getTotalVertices();
  25175. if (!totalVertices || !this.getIndices()) {
  25176. return null;
  25177. }
  25178. // Check if we need to recreate the submeshes
  25179. if (this.subMeshes && this.subMeshes.length > 0) {
  25180. var ib = this.getIndices();
  25181. if (!ib) {
  25182. return null;
  25183. }
  25184. var totalIndices = ib.length;
  25185. var needToRecreate = false;
  25186. if (force) {
  25187. needToRecreate = true;
  25188. }
  25189. else {
  25190. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25191. var submesh = _a[_i];
  25192. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25193. needToRecreate = true;
  25194. break;
  25195. }
  25196. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25197. needToRecreate = true;
  25198. break;
  25199. }
  25200. }
  25201. }
  25202. if (!needToRecreate) {
  25203. return this.subMeshes[0];
  25204. }
  25205. }
  25206. this.releaseSubMeshes();
  25207. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25208. };
  25209. Mesh.prototype.subdivide = function (count) {
  25210. if (count < 1) {
  25211. return;
  25212. }
  25213. var totalIndices = this.getTotalIndices();
  25214. var subdivisionSize = (totalIndices / count) | 0;
  25215. var offset = 0;
  25216. // Ensure that subdivisionSize is a multiple of 3
  25217. while (subdivisionSize % 3 !== 0) {
  25218. subdivisionSize++;
  25219. }
  25220. this.releaseSubMeshes();
  25221. for (var index = 0; index < count; index++) {
  25222. if (offset >= totalIndices) {
  25223. break;
  25224. }
  25225. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25226. offset += subdivisionSize;
  25227. }
  25228. this.synchronizeInstances();
  25229. };
  25230. /**
  25231. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25232. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25233. * The `data` are either a numeric array either a Float32Array.
  25234. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25235. * 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).
  25236. * Note that a new underlying VertexBuffer object is created each call.
  25237. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25238. *
  25239. * Possible `kind` values :
  25240. * - BABYLON.VertexBuffer.PositionKind
  25241. * - BABYLON.VertexBuffer.UVKind
  25242. * - BABYLON.VertexBuffer.UV2Kind
  25243. * - BABYLON.VertexBuffer.UV3Kind
  25244. * - BABYLON.VertexBuffer.UV4Kind
  25245. * - BABYLON.VertexBuffer.UV5Kind
  25246. * - BABYLON.VertexBuffer.UV6Kind
  25247. * - BABYLON.VertexBuffer.ColorKind
  25248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25252. *
  25253. * Returns the Mesh.
  25254. */
  25255. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25256. if (updatable === void 0) { updatable = false; }
  25257. if (!this._geometry) {
  25258. var vertexData = new BABYLON.VertexData();
  25259. vertexData.set(data, kind);
  25260. var scene = this.getScene();
  25261. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25262. }
  25263. else {
  25264. this._geometry.setVerticesData(kind, data, updatable, stride);
  25265. }
  25266. return this;
  25267. };
  25268. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25269. if (updatable === void 0) { updatable = true; }
  25270. var vb = this.getVertexBuffer(kind);
  25271. if (!vb || vb.isUpdatable() === updatable) {
  25272. return;
  25273. }
  25274. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25275. };
  25276. /**
  25277. * Sets the mesh VertexBuffer.
  25278. * Returns the Mesh.
  25279. */
  25280. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25281. if (!this._geometry) {
  25282. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25283. }
  25284. this._geometry.setVerticesBuffer(buffer);
  25285. return this;
  25286. };
  25287. /**
  25288. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25289. * If the mesh has no geometry, it is simply returned as it is.
  25290. * The `data` are either a numeric array either a Float32Array.
  25291. * No new underlying VertexBuffer object is created.
  25292. * 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.
  25293. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25294. *
  25295. * Possible `kind` values :
  25296. * - BABYLON.VertexBuffer.PositionKind
  25297. * - BABYLON.VertexBuffer.UVKind
  25298. * - BABYLON.VertexBuffer.UV2Kind
  25299. * - BABYLON.VertexBuffer.UV3Kind
  25300. * - BABYLON.VertexBuffer.UV4Kind
  25301. * - BABYLON.VertexBuffer.UV5Kind
  25302. * - BABYLON.VertexBuffer.UV6Kind
  25303. * - BABYLON.VertexBuffer.ColorKind
  25304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25308. *
  25309. * Returns the Mesh.
  25310. */
  25311. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25312. if (!this._geometry) {
  25313. return this;
  25314. }
  25315. if (!makeItUnique) {
  25316. this._geometry.updateVerticesData(kind, data, updateExtends);
  25317. }
  25318. else {
  25319. this.makeGeometryUnique();
  25320. this.updateVerticesData(kind, data, updateExtends, false);
  25321. }
  25322. return this;
  25323. };
  25324. /**
  25325. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25326. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25327. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25328. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25329. * Returns the Mesh.
  25330. */
  25331. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25332. if (computeNormals === void 0) { computeNormals = true; }
  25333. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25334. if (!positions) {
  25335. return this;
  25336. }
  25337. positionFunction(positions);
  25338. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25339. if (computeNormals) {
  25340. var indices = this.getIndices();
  25341. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25342. if (!normals) {
  25343. return this;
  25344. }
  25345. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25346. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25347. }
  25348. return this;
  25349. };
  25350. /**
  25351. * Creates a un-shared specific occurence of the geometry for the mesh.
  25352. * Returns the Mesh.
  25353. */
  25354. Mesh.prototype.makeGeometryUnique = function () {
  25355. if (!this._geometry) {
  25356. return this;
  25357. }
  25358. var oldGeometry = this._geometry;
  25359. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25360. oldGeometry.releaseForMesh(this, true);
  25361. geometry.applyToMesh(this);
  25362. return this;
  25363. };
  25364. /**
  25365. * Sets the mesh indices.
  25366. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25367. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25368. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25369. * This method creates a new index buffer each call.
  25370. * Returns the Mesh.
  25371. */
  25372. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25373. if (totalVertices === void 0) { totalVertices = null; }
  25374. if (updatable === void 0) { updatable = false; }
  25375. if (!this._geometry) {
  25376. var vertexData = new BABYLON.VertexData();
  25377. vertexData.indices = indices;
  25378. var scene = this.getScene();
  25379. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25380. }
  25381. else {
  25382. this._geometry.setIndices(indices, totalVertices, updatable);
  25383. }
  25384. return this;
  25385. };
  25386. /**
  25387. * Update the current index buffer
  25388. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25389. * Returns the Mesh.
  25390. */
  25391. Mesh.prototype.updateIndices = function (indices, offset) {
  25392. if (!this._geometry) {
  25393. return this;
  25394. }
  25395. this._geometry.updateIndices(indices, offset);
  25396. return this;
  25397. };
  25398. /**
  25399. * Invert the geometry to move from a right handed system to a left handed one.
  25400. * Returns the Mesh.
  25401. */
  25402. Mesh.prototype.toLeftHanded = function () {
  25403. if (!this._geometry) {
  25404. return this;
  25405. }
  25406. this._geometry.toLeftHanded();
  25407. return this;
  25408. };
  25409. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25410. if (!this._geometry) {
  25411. return this;
  25412. }
  25413. var engine = this.getScene().getEngine();
  25414. // Wireframe
  25415. var indexToBind;
  25416. if (this._unIndexed) {
  25417. indexToBind = null;
  25418. }
  25419. else {
  25420. switch (fillMode) {
  25421. case BABYLON.Material.PointFillMode:
  25422. indexToBind = null;
  25423. break;
  25424. case BABYLON.Material.WireFrameFillMode:
  25425. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25426. break;
  25427. default:
  25428. case BABYLON.Material.TriangleFillMode:
  25429. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25430. break;
  25431. }
  25432. }
  25433. // VBOs
  25434. this._geometry._bind(effect, indexToBind);
  25435. return this;
  25436. };
  25437. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25438. if (alternate === void 0) { alternate = false; }
  25439. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25440. return this;
  25441. }
  25442. this.onBeforeDrawObservable.notifyObservers(this);
  25443. var scene = this.getScene();
  25444. var engine = scene.getEngine();
  25445. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25446. // or triangles as points
  25447. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25448. }
  25449. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25450. // Triangles as wireframe
  25451. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25452. }
  25453. else {
  25454. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25455. }
  25456. if (scene._isAlternateRenderingEnabled && !alternate) {
  25457. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25458. if (!effect || !scene.activeCamera) {
  25459. return this;
  25460. }
  25461. scene._switchToAlternateCameraConfiguration(true);
  25462. this._effectiveMaterial.bindView(effect);
  25463. this._effectiveMaterial.bindViewProjection(effect);
  25464. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25465. this._draw(subMesh, fillMode, instancesCount, true);
  25466. engine.setViewport(scene.activeCamera.viewport);
  25467. scene._switchToAlternateCameraConfiguration(false);
  25468. this._effectiveMaterial.bindView(effect);
  25469. this._effectiveMaterial.bindViewProjection(effect);
  25470. }
  25471. return this;
  25472. };
  25473. /**
  25474. * Registers for this mesh a javascript function called just before the rendering process.
  25475. * This function is passed the current mesh.
  25476. * Return the Mesh.
  25477. */
  25478. Mesh.prototype.registerBeforeRender = function (func) {
  25479. this.onBeforeRenderObservable.add(func);
  25480. return this;
  25481. };
  25482. /**
  25483. * Disposes a previously registered javascript function called before the rendering.
  25484. * This function is passed the current mesh.
  25485. * Returns the Mesh.
  25486. */
  25487. Mesh.prototype.unregisterBeforeRender = function (func) {
  25488. this.onBeforeRenderObservable.removeCallback(func);
  25489. return this;
  25490. };
  25491. /**
  25492. * Registers for this mesh a javascript function called just after the rendering is complete.
  25493. * This function is passed the current mesh.
  25494. * Returns the Mesh.
  25495. */
  25496. Mesh.prototype.registerAfterRender = function (func) {
  25497. this.onAfterRenderObservable.add(func);
  25498. return this;
  25499. };
  25500. /**
  25501. * Disposes a previously registered javascript function called after the rendering.
  25502. * This function is passed the current mesh.
  25503. * Return the Mesh.
  25504. */
  25505. Mesh.prototype.unregisterAfterRender = function (func) {
  25506. this.onAfterRenderObservable.removeCallback(func);
  25507. return this;
  25508. };
  25509. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25510. var scene = this.getScene();
  25511. this._batchCache.mustReturn = false;
  25512. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25513. this._batchCache.visibleInstances[subMeshId] = null;
  25514. if (this._visibleInstances) {
  25515. var currentRenderId = scene.getRenderId();
  25516. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25517. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25518. var selfRenderId = this._renderId;
  25519. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25520. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25521. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25522. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25523. }
  25524. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25525. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25526. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25527. this._batchCache.mustReturn = true;
  25528. return this._batchCache;
  25529. }
  25530. if (currentRenderId !== selfRenderId) {
  25531. this._batchCache.renderSelf[subMeshId] = false;
  25532. }
  25533. }
  25534. this._renderIdForInstances[subMeshId] = currentRenderId;
  25535. }
  25536. return this._batchCache;
  25537. };
  25538. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25539. var visibleInstances = batch.visibleInstances[subMesh._id];
  25540. if (!visibleInstances) {
  25541. return this;
  25542. }
  25543. var matricesCount = visibleInstances.length + 1;
  25544. var bufferSize = matricesCount * 16 * 4;
  25545. var currentInstancesBufferSize = this._instancesBufferSize;
  25546. var instancesBuffer = this._instancesBuffer;
  25547. while (this._instancesBufferSize < bufferSize) {
  25548. this._instancesBufferSize *= 2;
  25549. }
  25550. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25551. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25552. }
  25553. var offset = 0;
  25554. var instancesCount = 0;
  25555. var world = this.getWorldMatrix();
  25556. if (batch.renderSelf[subMesh._id]) {
  25557. world.copyToArray(this._instancesData, offset);
  25558. offset += 16;
  25559. instancesCount++;
  25560. }
  25561. if (visibleInstances) {
  25562. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25563. var instance = visibleInstances[instanceIndex];
  25564. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25565. offset += 16;
  25566. instancesCount++;
  25567. }
  25568. }
  25569. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25570. if (instancesBuffer) {
  25571. instancesBuffer.dispose();
  25572. }
  25573. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25574. this._instancesBuffer = instancesBuffer;
  25575. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25576. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25577. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25578. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25579. }
  25580. else {
  25581. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25582. }
  25583. this._bind(subMesh, effect, fillMode);
  25584. this._draw(subMesh, fillMode, instancesCount);
  25585. engine.unbindInstanceAttributes();
  25586. return this;
  25587. };
  25588. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25589. var scene = this.getScene();
  25590. var engine = scene.getEngine();
  25591. if (hardwareInstancedRendering) {
  25592. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25593. }
  25594. else {
  25595. if (batch.renderSelf[subMesh._id]) {
  25596. // Draw
  25597. if (onBeforeDraw) {
  25598. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25599. }
  25600. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25601. }
  25602. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25603. if (visibleInstancesForSubMesh) {
  25604. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25605. var instance = visibleInstancesForSubMesh[instanceIndex];
  25606. // World
  25607. var world = instance.getWorldMatrix();
  25608. if (onBeforeDraw) {
  25609. onBeforeDraw(true, world, effectiveMaterial);
  25610. }
  25611. // Draw
  25612. this._draw(subMesh, fillMode);
  25613. }
  25614. }
  25615. }
  25616. return this;
  25617. };
  25618. /**
  25619. * Triggers the draw call for the mesh.
  25620. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25621. * Returns the Mesh.
  25622. */
  25623. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25624. this.checkOcclusionQuery();
  25625. if (this._isOccluded) {
  25626. return this;
  25627. }
  25628. var scene = this.getScene();
  25629. // Managing instances
  25630. var batch = this._getInstancesRenderList(subMesh._id);
  25631. if (batch.mustReturn) {
  25632. return this;
  25633. }
  25634. // Checking geometry state
  25635. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25636. return this;
  25637. }
  25638. this.onBeforeRenderObservable.notifyObservers(this);
  25639. var engine = scene.getEngine();
  25640. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25641. // Material
  25642. var material = subMesh.getMaterial();
  25643. if (!material) {
  25644. return this;
  25645. }
  25646. this._effectiveMaterial = material;
  25647. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25648. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25649. return this;
  25650. }
  25651. }
  25652. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25653. return this;
  25654. }
  25655. // Alpha mode
  25656. if (enableAlphaMode) {
  25657. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25658. }
  25659. // Outline - step 1
  25660. var savedDepthWrite = engine.getDepthWrite();
  25661. if (this.renderOutline) {
  25662. engine.setDepthWrite(false);
  25663. scene.getOutlineRenderer().render(subMesh, batch);
  25664. engine.setDepthWrite(savedDepthWrite);
  25665. }
  25666. var effect;
  25667. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25668. effect = subMesh.effect;
  25669. }
  25670. else {
  25671. effect = this._effectiveMaterial.getEffect();
  25672. }
  25673. if (!effect) {
  25674. return this;
  25675. }
  25676. var sideOrientation = this.overrideMaterialSideOrientation;
  25677. if (sideOrientation == null) {
  25678. sideOrientation = this._effectiveMaterial.sideOrientation;
  25679. if (this._getWorldMatrixDeterminant() < 0) {
  25680. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25681. }
  25682. }
  25683. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25684. if (this._effectiveMaterial.forceDepthWrite) {
  25685. engine.setDepthWrite(true);
  25686. }
  25687. // Bind
  25688. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25689. if (!hardwareInstancedRendering) {
  25690. this._bind(subMesh, effect, fillMode);
  25691. }
  25692. var world = this.getWorldMatrix();
  25693. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25694. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25695. }
  25696. else {
  25697. this._effectiveMaterial.bind(world, this);
  25698. }
  25699. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25700. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25701. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25702. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25703. }
  25704. // Draw
  25705. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25706. // Unbind
  25707. this._effectiveMaterial.unbind();
  25708. // Outline - step 2
  25709. if (this.renderOutline && savedDepthWrite) {
  25710. engine.setDepthWrite(true);
  25711. engine.setColorWrite(false);
  25712. scene.getOutlineRenderer().render(subMesh, batch);
  25713. engine.setColorWrite(true);
  25714. }
  25715. // Overlay
  25716. if (this.renderOverlay) {
  25717. var currentMode = engine.getAlphaMode();
  25718. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25719. scene.getOutlineRenderer().render(subMesh, batch, true);
  25720. engine.setAlphaMode(currentMode);
  25721. }
  25722. this.onAfterRenderObservable.notifyObservers(this);
  25723. return this;
  25724. };
  25725. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25726. if (isInstance && effectiveMaterial) {
  25727. effectiveMaterial.bindOnlyWorldMatrix(world);
  25728. }
  25729. };
  25730. /**
  25731. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25732. */
  25733. Mesh.prototype.getEmittedParticleSystems = function () {
  25734. var results = new Array();
  25735. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25736. var particleSystem = this.getScene().particleSystems[index];
  25737. if (particleSystem.emitter === this) {
  25738. results.push(particleSystem);
  25739. }
  25740. }
  25741. return results;
  25742. };
  25743. /**
  25744. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  25745. */
  25746. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  25747. var results = new Array();
  25748. var descendants = this.getDescendants();
  25749. descendants.push(this);
  25750. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25751. var particleSystem = this.getScene().particleSystems[index];
  25752. var emitter = particleSystem.emitter;
  25753. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  25754. results.push(particleSystem);
  25755. }
  25756. }
  25757. return results;
  25758. };
  25759. Mesh.prototype._checkDelayState = function () {
  25760. var scene = this.getScene();
  25761. if (this._geometry) {
  25762. this._geometry.load(scene);
  25763. }
  25764. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25766. this._queueLoad(scene);
  25767. }
  25768. return this;
  25769. };
  25770. Mesh.prototype._queueLoad = function (scene) {
  25771. var _this = this;
  25772. scene._addPendingData(this);
  25773. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  25774. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25775. if (data instanceof ArrayBuffer) {
  25776. _this._delayLoadingFunction(data, _this);
  25777. }
  25778. else {
  25779. _this._delayLoadingFunction(JSON.parse(data), _this);
  25780. }
  25781. _this.instances.forEach(function (instance) {
  25782. instance._syncSubMeshes();
  25783. });
  25784. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25785. scene._removePendingData(_this);
  25786. }, function () { }, scene.database, getBinaryData);
  25787. return this;
  25788. };
  25789. /**
  25790. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  25791. */
  25792. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  25793. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25794. return false;
  25795. }
  25796. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  25797. return false;
  25798. }
  25799. this._checkDelayState();
  25800. return true;
  25801. };
  25802. /**
  25803. * Sets the mesh material by the material or multiMaterial `id` property.
  25804. * The material `id` is a string identifying the material or the multiMaterial.
  25805. * This method returns the Mesh.
  25806. */
  25807. Mesh.prototype.setMaterialByID = function (id) {
  25808. var materials = this.getScene().materials;
  25809. var index;
  25810. for (index = materials.length - 1; index > -1; index--) {
  25811. if (materials[index].id === id) {
  25812. this.material = materials[index];
  25813. return this;
  25814. }
  25815. }
  25816. // Multi
  25817. var multiMaterials = this.getScene().multiMaterials;
  25818. for (index = multiMaterials.length - 1; index > -1; index--) {
  25819. if (multiMaterials[index].id === id) {
  25820. this.material = multiMaterials[index];
  25821. return this;
  25822. }
  25823. }
  25824. return this;
  25825. };
  25826. /**
  25827. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  25828. */
  25829. Mesh.prototype.getAnimatables = function () {
  25830. var results = new Array();
  25831. if (this.material) {
  25832. results.push(this.material);
  25833. }
  25834. if (this.skeleton) {
  25835. results.push(this.skeleton);
  25836. }
  25837. return results;
  25838. };
  25839. /**
  25840. * Modifies the mesh geometry according to the passed transformation matrix.
  25841. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  25842. * The mesh normals are modified accordingly the same transformation.
  25843. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25844. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25845. * Returns the Mesh.
  25846. */
  25847. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  25848. // Position
  25849. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25850. return this;
  25851. }
  25852. var submeshes = this.subMeshes.splice(0);
  25853. this._resetPointsArrayCache();
  25854. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25855. var temp = new Array();
  25856. var index;
  25857. for (index = 0; index < data.length; index += 3) {
  25858. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  25859. }
  25860. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  25861. // Normals
  25862. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25863. return this;
  25864. }
  25865. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25866. temp = [];
  25867. for (index = 0; index < data.length; index += 3) {
  25868. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  25869. }
  25870. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  25871. // flip faces?
  25872. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  25873. this.flipFaces();
  25874. }
  25875. // Restore submeshes
  25876. this.releaseSubMeshes();
  25877. this.subMeshes = submeshes;
  25878. return this;
  25879. };
  25880. /**
  25881. * Modifies the mesh geometry according to its own current World Matrix.
  25882. * The mesh World Matrix is then reset.
  25883. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  25884. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  25885. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25886. * Returns the Mesh.
  25887. */
  25888. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  25889. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  25890. this.scaling.copyFromFloats(1, 1, 1);
  25891. this.position.copyFromFloats(0, 0, 0);
  25892. this.rotation.copyFromFloats(0, 0, 0);
  25893. //only if quaternion is already set
  25894. if (this.rotationQuaternion) {
  25895. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25896. }
  25897. this._worldMatrix = BABYLON.Matrix.Identity();
  25898. return this;
  25899. };
  25900. Object.defineProperty(Mesh.prototype, "_positions", {
  25901. // Cache
  25902. get: function () {
  25903. if (this._geometry) {
  25904. return this._geometry._positions;
  25905. }
  25906. return null;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. Mesh.prototype._resetPointsArrayCache = function () {
  25912. if (this._geometry) {
  25913. this._geometry._resetPointsArrayCache();
  25914. }
  25915. return this;
  25916. };
  25917. Mesh.prototype._generatePointsArray = function () {
  25918. if (this._geometry) {
  25919. return this._geometry._generatePointsArray();
  25920. }
  25921. return false;
  25922. };
  25923. /**
  25924. * Returns a new Mesh object generated from the current mesh properties.
  25925. * This method must not get confused with createInstance().
  25926. * The parameter `name` is a string, the name given to the new mesh.
  25927. * The optional parameter `newParent` can be any Node object (default `null`).
  25928. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25929. * 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.
  25930. */
  25931. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25932. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25933. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25934. };
  25935. /**
  25936. * Disposes the Mesh.
  25937. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  25938. * Returns nothing.
  25939. */
  25940. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  25941. var _this = this;
  25942. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  25943. this.morphTargetManager = null;
  25944. if (this._geometry) {
  25945. this._geometry.releaseForMesh(this, true);
  25946. }
  25947. // Sources
  25948. var meshes = this.getScene().meshes;
  25949. meshes.forEach(function (abstractMesh) {
  25950. var mesh = abstractMesh;
  25951. if (mesh._source && mesh._source === _this) {
  25952. mesh._source = null;
  25953. }
  25954. });
  25955. this._source = null;
  25956. // Instances
  25957. if (this._instancesBuffer) {
  25958. this._instancesBuffer.dispose();
  25959. this._instancesBuffer = null;
  25960. }
  25961. while (this.instances.length) {
  25962. this.instances[0].dispose();
  25963. }
  25964. // Highlight layers.
  25965. var highlightLayers = this.getScene().highlightLayers;
  25966. for (var i = 0; i < highlightLayers.length; i++) {
  25967. var highlightLayer = highlightLayers[i];
  25968. if (highlightLayer) {
  25969. highlightLayer.removeMesh(this);
  25970. highlightLayer.removeExcludedMesh(this);
  25971. }
  25972. }
  25973. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25974. };
  25975. /**
  25976. * Modifies the mesh geometry according to a displacement map.
  25977. * 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.
  25978. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25979. * This method returns nothing.
  25980. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25981. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25982. * 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.
  25983. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25984. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25985. *
  25986. * Returns the Mesh.
  25987. */
  25988. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25989. var _this = this;
  25990. var scene = this.getScene();
  25991. var onload = function (img) {
  25992. // Getting height map data
  25993. var canvas = document.createElement("canvas");
  25994. var context = canvas.getContext("2d");
  25995. var heightMapWidth = img.width;
  25996. var heightMapHeight = img.height;
  25997. canvas.width = heightMapWidth;
  25998. canvas.height = heightMapHeight;
  25999. context.drawImage(img, 0, 0);
  26000. // Create VertexData from map data
  26001. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26002. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26003. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26004. //execute success callback, if set
  26005. if (onSuccess) {
  26006. onSuccess(_this);
  26007. }
  26008. };
  26009. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26010. return this;
  26011. };
  26012. /**
  26013. * Modifies the mesh geometry according to a displacementMap buffer.
  26014. * 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.
  26015. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26016. * This method returns nothing.
  26017. * 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.
  26018. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26019. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26020. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26021. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26022. *
  26023. * Returns the Mesh.
  26024. */
  26025. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26026. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26027. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26028. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26029. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26030. return this;
  26031. }
  26032. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26033. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26034. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26035. var position = BABYLON.Vector3.Zero();
  26036. var normal = BABYLON.Vector3.Zero();
  26037. var uv = BABYLON.Vector2.Zero();
  26038. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26039. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26040. for (var index = 0; index < positions.length; index += 3) {
  26041. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26042. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26043. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26044. // Compute height
  26045. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26046. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26047. var pos = (u + v * heightMapWidth) * 4;
  26048. var r = buffer[pos] / 255.0;
  26049. var g = buffer[pos + 1] / 255.0;
  26050. var b = buffer[pos + 2] / 255.0;
  26051. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26052. normal.normalize();
  26053. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26054. position = position.add(normal);
  26055. position.toArray(positions, index);
  26056. }
  26057. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26058. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26059. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26060. return this;
  26061. };
  26062. /**
  26063. * Modify the mesh to get a flat shading rendering.
  26064. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26065. * This method returns the Mesh.
  26066. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26067. */
  26068. Mesh.prototype.convertToFlatShadedMesh = function () {
  26069. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26070. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26071. var kinds = this.getVerticesDataKinds();
  26072. var vbs = {};
  26073. var data = {};
  26074. var newdata = {};
  26075. var updatableNormals = false;
  26076. var kindIndex;
  26077. var kind;
  26078. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26079. kind = kinds[kindIndex];
  26080. var vertexBuffer = this.getVertexBuffer(kind);
  26081. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26082. updatableNormals = vertexBuffer.isUpdatable();
  26083. kinds.splice(kindIndex, 1);
  26084. kindIndex--;
  26085. continue;
  26086. }
  26087. vbs[kind] = vertexBuffer;
  26088. data[kind] = vbs[kind].getData();
  26089. newdata[kind] = [];
  26090. }
  26091. // Save previous submeshes
  26092. var previousSubmeshes = this.subMeshes.slice(0);
  26093. var indices = this.getIndices();
  26094. var totalIndices = this.getTotalIndices();
  26095. // Generating unique vertices per face
  26096. var index;
  26097. for (index = 0; index < totalIndices; index++) {
  26098. var vertexIndex = indices[index];
  26099. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26100. kind = kinds[kindIndex];
  26101. var stride = vbs[kind].getStrideSize();
  26102. for (var offset = 0; offset < stride; offset++) {
  26103. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26104. }
  26105. }
  26106. }
  26107. // Updating faces & normal
  26108. var normals = [];
  26109. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26110. for (index = 0; index < totalIndices; index += 3) {
  26111. indices[index] = index;
  26112. indices[index + 1] = index + 1;
  26113. indices[index + 2] = index + 2;
  26114. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26115. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26116. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26117. var p1p2 = p1.subtract(p2);
  26118. var p3p2 = p3.subtract(p2);
  26119. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26120. // Store same normals for every vertex
  26121. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26122. normals.push(normal.x);
  26123. normals.push(normal.y);
  26124. normals.push(normal.z);
  26125. }
  26126. }
  26127. this.setIndices(indices);
  26128. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26129. // Updating vertex buffers
  26130. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26131. kind = kinds[kindIndex];
  26132. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26133. }
  26134. // Updating submeshes
  26135. this.releaseSubMeshes();
  26136. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26137. var previousOne = previousSubmeshes[submeshIndex];
  26138. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26139. }
  26140. this.synchronizeInstances();
  26141. return this;
  26142. };
  26143. /**
  26144. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26145. * In other words, more vertices, no more indices and a single bigger VBO.
  26146. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26147. * Returns the Mesh.
  26148. */
  26149. Mesh.prototype.convertToUnIndexedMesh = function () {
  26150. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26151. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26152. var kinds = this.getVerticesDataKinds();
  26153. var vbs = {};
  26154. var data = {};
  26155. var newdata = {};
  26156. var kindIndex;
  26157. var kind;
  26158. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26159. kind = kinds[kindIndex];
  26160. var vertexBuffer = this.getVertexBuffer(kind);
  26161. vbs[kind] = vertexBuffer;
  26162. data[kind] = vbs[kind].getData();
  26163. newdata[kind] = [];
  26164. }
  26165. // Save previous submeshes
  26166. var previousSubmeshes = this.subMeshes.slice(0);
  26167. var indices = this.getIndices();
  26168. var totalIndices = this.getTotalIndices();
  26169. // Generating unique vertices per face
  26170. var index;
  26171. for (index = 0; index < totalIndices; index++) {
  26172. var vertexIndex = indices[index];
  26173. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26174. kind = kinds[kindIndex];
  26175. var stride = vbs[kind].getStrideSize();
  26176. for (var offset = 0; offset < stride; offset++) {
  26177. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26178. }
  26179. }
  26180. }
  26181. // Updating indices
  26182. for (index = 0; index < totalIndices; index += 3) {
  26183. indices[index] = index;
  26184. indices[index + 1] = index + 1;
  26185. indices[index + 2] = index + 2;
  26186. }
  26187. this.setIndices(indices);
  26188. // Updating vertex buffers
  26189. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26190. kind = kinds[kindIndex];
  26191. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26192. }
  26193. // Updating submeshes
  26194. this.releaseSubMeshes();
  26195. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26196. var previousOne = previousSubmeshes[submeshIndex];
  26197. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26198. }
  26199. this._unIndexed = true;
  26200. this.synchronizeInstances();
  26201. return this;
  26202. };
  26203. /**
  26204. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26205. * This method returns the Mesh.
  26206. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26207. */
  26208. Mesh.prototype.flipFaces = function (flipNormals) {
  26209. if (flipNormals === void 0) { flipNormals = false; }
  26210. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26211. var i;
  26212. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26213. for (i = 0; i < vertex_data.normals.length; i++) {
  26214. vertex_data.normals[i] *= -1;
  26215. }
  26216. }
  26217. if (vertex_data.indices) {
  26218. var temp;
  26219. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26220. // reassign indices
  26221. temp = vertex_data.indices[i + 1];
  26222. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26223. vertex_data.indices[i + 2] = temp;
  26224. }
  26225. }
  26226. vertex_data.applyToMesh(this);
  26227. return this;
  26228. };
  26229. // Instances
  26230. /**
  26231. * Creates a new InstancedMesh object from the mesh model.
  26232. * An instance shares the same properties and the same material than its model.
  26233. * Only these properties of each instance can then be set individually :
  26234. * - position
  26235. * - rotation
  26236. * - rotationQuaternion
  26237. * - setPivotMatrix
  26238. * - scaling
  26239. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26240. * Warning : this method is not supported for Line mesh and LineSystem
  26241. */
  26242. Mesh.prototype.createInstance = function (name) {
  26243. return new BABYLON.InstancedMesh(name, this);
  26244. };
  26245. /**
  26246. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26247. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26248. * This method returns the Mesh.
  26249. */
  26250. Mesh.prototype.synchronizeInstances = function () {
  26251. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26252. var instance = this.instances[instanceIndex];
  26253. instance._syncSubMeshes();
  26254. }
  26255. return this;
  26256. };
  26257. /**
  26258. * Simplify the mesh according to the given array of settings.
  26259. * Function will return immediately and will simplify async. It returns the Mesh.
  26260. * @param settings a collection of simplification settings.
  26261. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26262. * @param type the type of simplification to run.
  26263. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26264. */
  26265. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26266. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26267. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26268. this.getScene().simplificationQueue.addTask({
  26269. settings: settings,
  26270. parallelProcessing: parallelProcessing,
  26271. mesh: this,
  26272. simplificationType: simplificationType,
  26273. successCallback: successCallback
  26274. });
  26275. return this;
  26276. };
  26277. /**
  26278. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26279. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26280. * This should be used together with the simplification to avoid disappearing triangles.
  26281. * Returns the Mesh.
  26282. * @param successCallback an optional success callback to be called after the optimization finished.
  26283. */
  26284. Mesh.prototype.optimizeIndices = function (successCallback) {
  26285. var _this = this;
  26286. var indices = this.getIndices();
  26287. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26288. if (!positions || !indices) {
  26289. return this;
  26290. }
  26291. var vectorPositions = new Array();
  26292. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26293. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26294. }
  26295. var dupes = new Array();
  26296. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26297. var realPos = vectorPositions.length - 1 - iteration;
  26298. var testedPosition = vectorPositions[realPos];
  26299. for (var j = 0; j < realPos; ++j) {
  26300. var againstPosition = vectorPositions[j];
  26301. if (testedPosition.equals(againstPosition)) {
  26302. dupes[realPos] = j;
  26303. break;
  26304. }
  26305. }
  26306. }, function () {
  26307. for (var i = 0; i < indices.length; ++i) {
  26308. indices[i] = dupes[indices[i]] || indices[i];
  26309. }
  26310. //indices are now reordered
  26311. var originalSubMeshes = _this.subMeshes.slice(0);
  26312. _this.setIndices(indices);
  26313. _this.subMeshes = originalSubMeshes;
  26314. if (successCallback) {
  26315. successCallback(_this);
  26316. }
  26317. });
  26318. return this;
  26319. };
  26320. Mesh.prototype.serialize = function (serializationObject) {
  26321. serializationObject.name = this.name;
  26322. serializationObject.id = this.id;
  26323. serializationObject.type = this.getClassName();
  26324. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26325. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26326. }
  26327. serializationObject.position = this.position.asArray();
  26328. if (this.rotationQuaternion) {
  26329. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26330. }
  26331. else if (this.rotation) {
  26332. serializationObject.rotation = this.rotation.asArray();
  26333. }
  26334. serializationObject.scaling = this.scaling.asArray();
  26335. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26336. serializationObject.isEnabled = this.isEnabled(false);
  26337. serializationObject.isVisible = this.isVisible;
  26338. serializationObject.infiniteDistance = this.infiniteDistance;
  26339. serializationObject.pickable = this.isPickable;
  26340. serializationObject.receiveShadows = this.receiveShadows;
  26341. serializationObject.billboardMode = this.billboardMode;
  26342. serializationObject.visibility = this.visibility;
  26343. serializationObject.checkCollisions = this.checkCollisions;
  26344. serializationObject.isBlocker = this.isBlocker;
  26345. // Parent
  26346. if (this.parent) {
  26347. serializationObject.parentId = this.parent.id;
  26348. }
  26349. // Geometry
  26350. serializationObject.isUnIndexed = this.isUnIndexed;
  26351. var geometry = this._geometry;
  26352. if (geometry) {
  26353. var geometryId = geometry.id;
  26354. serializationObject.geometryId = geometryId;
  26355. // SubMeshes
  26356. serializationObject.subMeshes = [];
  26357. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26358. var subMesh = this.subMeshes[subIndex];
  26359. serializationObject.subMeshes.push({
  26360. materialIndex: subMesh.materialIndex,
  26361. verticesStart: subMesh.verticesStart,
  26362. verticesCount: subMesh.verticesCount,
  26363. indexStart: subMesh.indexStart,
  26364. indexCount: subMesh.indexCount
  26365. });
  26366. }
  26367. }
  26368. // Material
  26369. if (this.material) {
  26370. serializationObject.materialId = this.material.id;
  26371. }
  26372. else {
  26373. this.material = null;
  26374. }
  26375. // Morph targets
  26376. if (this.morphTargetManager) {
  26377. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26378. }
  26379. // Skeleton
  26380. if (this.skeleton) {
  26381. serializationObject.skeletonId = this.skeleton.id;
  26382. }
  26383. // Physics
  26384. //TODO implement correct serialization for physics impostors.
  26385. var impostor = this.getPhysicsImpostor();
  26386. if (impostor) {
  26387. serializationObject.physicsMass = impostor.getParam("mass");
  26388. serializationObject.physicsFriction = impostor.getParam("friction");
  26389. serializationObject.physicsRestitution = impostor.getParam("mass");
  26390. serializationObject.physicsImpostor = impostor.type;
  26391. }
  26392. // Metadata
  26393. if (this.metadata) {
  26394. serializationObject.metadata = this.metadata;
  26395. }
  26396. // Instances
  26397. serializationObject.instances = [];
  26398. for (var index = 0; index < this.instances.length; index++) {
  26399. var instance = this.instances[index];
  26400. var serializationInstance = {
  26401. name: instance.name,
  26402. id: instance.id,
  26403. position: instance.position.asArray(),
  26404. scaling: instance.scaling.asArray()
  26405. };
  26406. if (instance.rotationQuaternion) {
  26407. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26408. }
  26409. else if (instance.rotation) {
  26410. serializationInstance.rotation = instance.rotation.asArray();
  26411. }
  26412. serializationObject.instances.push(serializationInstance);
  26413. // Animations
  26414. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26415. serializationInstance.ranges = instance.serializeAnimationRanges();
  26416. }
  26417. //
  26418. // Animations
  26419. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26420. serializationObject.ranges = this.serializeAnimationRanges();
  26421. // Layer mask
  26422. serializationObject.layerMask = this.layerMask;
  26423. // Alpha
  26424. serializationObject.alphaIndex = this.alphaIndex;
  26425. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26426. // Overlay
  26427. serializationObject.overlayAlpha = this.overlayAlpha;
  26428. serializationObject.overlayColor = this.overlayColor.asArray();
  26429. serializationObject.renderOverlay = this.renderOverlay;
  26430. // Fog
  26431. serializationObject.applyFog = this.applyFog;
  26432. // Action Manager
  26433. if (this.actionManager) {
  26434. serializationObject.actions = this.actionManager.serialize(this.name);
  26435. }
  26436. };
  26437. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26438. if (!this.geometry) {
  26439. return;
  26440. }
  26441. this._markSubMeshesAsAttributesDirty();
  26442. var morphTargetManager = this._morphTargetManager;
  26443. if (morphTargetManager && morphTargetManager.vertexCount) {
  26444. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26445. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26446. this.morphTargetManager = null;
  26447. return;
  26448. }
  26449. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26450. var morphTarget = morphTargetManager.getActiveTarget(index);
  26451. var positions = morphTarget.getPositions();
  26452. if (!positions) {
  26453. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26454. return;
  26455. }
  26456. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26457. var normals = morphTarget.getNormals();
  26458. if (normals) {
  26459. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26460. }
  26461. var tangents = morphTarget.getTangents();
  26462. if (tangents) {
  26463. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26464. }
  26465. }
  26466. }
  26467. else {
  26468. var index = 0;
  26469. // Positions
  26470. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26471. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26472. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26473. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26474. }
  26475. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26476. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26477. }
  26478. index++;
  26479. }
  26480. }
  26481. };
  26482. // Statics
  26483. /**
  26484. * Returns a new Mesh object parsed from the source provided.
  26485. * The parameter `parsedMesh` is the source.
  26486. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26487. */
  26488. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26489. var mesh;
  26490. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26491. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26492. }
  26493. else {
  26494. mesh = new Mesh(parsedMesh.name, scene);
  26495. }
  26496. mesh.id = parsedMesh.id;
  26497. if (BABYLON.Tags) {
  26498. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26499. }
  26500. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26501. if (parsedMesh.metadata !== undefined) {
  26502. mesh.metadata = parsedMesh.metadata;
  26503. }
  26504. if (parsedMesh.rotationQuaternion) {
  26505. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26506. }
  26507. else if (parsedMesh.rotation) {
  26508. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26509. }
  26510. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26511. if (parsedMesh.localMatrix) {
  26512. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26513. }
  26514. else if (parsedMesh.pivotMatrix) {
  26515. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26516. }
  26517. mesh.setEnabled(parsedMesh.isEnabled);
  26518. mesh.isVisible = parsedMesh.isVisible;
  26519. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26520. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26521. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26522. if (parsedMesh.applyFog !== undefined) {
  26523. mesh.applyFog = parsedMesh.applyFog;
  26524. }
  26525. if (parsedMesh.pickable !== undefined) {
  26526. mesh.isPickable = parsedMesh.pickable;
  26527. }
  26528. if (parsedMesh.alphaIndex !== undefined) {
  26529. mesh.alphaIndex = parsedMesh.alphaIndex;
  26530. }
  26531. mesh.receiveShadows = parsedMesh.receiveShadows;
  26532. mesh.billboardMode = parsedMesh.billboardMode;
  26533. if (parsedMesh.visibility !== undefined) {
  26534. mesh.visibility = parsedMesh.visibility;
  26535. }
  26536. mesh.checkCollisions = parsedMesh.checkCollisions;
  26537. if (parsedMesh.isBlocker !== undefined) {
  26538. mesh.isBlocker = parsedMesh.isBlocker;
  26539. }
  26540. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26541. // freezeWorldMatrix
  26542. if (parsedMesh.freezeWorldMatrix) {
  26543. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26544. }
  26545. // Parent
  26546. if (parsedMesh.parentId) {
  26547. mesh._waitingParentId = parsedMesh.parentId;
  26548. }
  26549. // Actions
  26550. if (parsedMesh.actions !== undefined) {
  26551. mesh._waitingActions = parsedMesh.actions;
  26552. }
  26553. // Overlay
  26554. if (parsedMesh.overlayAlpha !== undefined) {
  26555. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26556. }
  26557. if (parsedMesh.overlayColor !== undefined) {
  26558. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26559. }
  26560. if (parsedMesh.renderOverlay !== undefined) {
  26561. mesh.renderOverlay = parsedMesh.renderOverlay;
  26562. }
  26563. // Geometry
  26564. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26565. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26566. if (parsedMesh.delayLoadingFile) {
  26567. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26568. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26569. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26570. if (parsedMesh._binaryInfo) {
  26571. mesh._binaryInfo = parsedMesh._binaryInfo;
  26572. }
  26573. mesh._delayInfo = [];
  26574. if (parsedMesh.hasUVs) {
  26575. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26576. }
  26577. if (parsedMesh.hasUVs2) {
  26578. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26579. }
  26580. if (parsedMesh.hasUVs3) {
  26581. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26582. }
  26583. if (parsedMesh.hasUVs4) {
  26584. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26585. }
  26586. if (parsedMesh.hasUVs5) {
  26587. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26588. }
  26589. if (parsedMesh.hasUVs6) {
  26590. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26591. }
  26592. if (parsedMesh.hasColors) {
  26593. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26594. }
  26595. if (parsedMesh.hasMatricesIndices) {
  26596. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26597. }
  26598. if (parsedMesh.hasMatricesWeights) {
  26599. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26600. }
  26601. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26602. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26603. mesh._checkDelayState();
  26604. }
  26605. }
  26606. else {
  26607. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26608. }
  26609. // Material
  26610. if (parsedMesh.materialId) {
  26611. mesh.setMaterialByID(parsedMesh.materialId);
  26612. }
  26613. else {
  26614. mesh.material = null;
  26615. }
  26616. // Morph targets
  26617. if (parsedMesh.morphTargetManagerId > -1) {
  26618. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26619. }
  26620. // Skeleton
  26621. if (parsedMesh.skeletonId > -1) {
  26622. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26623. if (parsedMesh.numBoneInfluencers) {
  26624. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26625. }
  26626. }
  26627. // Animations
  26628. if (parsedMesh.animations) {
  26629. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26630. var parsedAnimation = parsedMesh.animations[animationIndex];
  26631. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26632. }
  26633. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26634. }
  26635. if (parsedMesh.autoAnimate) {
  26636. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26637. }
  26638. // Layer Mask
  26639. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26640. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26641. }
  26642. else {
  26643. mesh.layerMask = 0x0FFFFFFF;
  26644. }
  26645. // Physics
  26646. if (parsedMesh.physicsImpostor) {
  26647. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26648. mass: parsedMesh.physicsMass,
  26649. friction: parsedMesh.physicsFriction,
  26650. restitution: parsedMesh.physicsRestitution
  26651. }, scene);
  26652. }
  26653. // Instances
  26654. if (parsedMesh.instances) {
  26655. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26656. var parsedInstance = parsedMesh.instances[index];
  26657. var instance = mesh.createInstance(parsedInstance.name);
  26658. if (parsedInstance.id) {
  26659. instance.id = parsedInstance.id;
  26660. }
  26661. if (BABYLON.Tags) {
  26662. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26663. }
  26664. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26665. if (parsedInstance.parentId) {
  26666. instance._waitingParentId = parsedInstance.parentId;
  26667. }
  26668. if (parsedInstance.rotationQuaternion) {
  26669. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26670. }
  26671. else if (parsedInstance.rotation) {
  26672. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26673. }
  26674. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26675. instance.checkCollisions = mesh.checkCollisions;
  26676. if (parsedMesh.animations) {
  26677. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26678. parsedAnimation = parsedMesh.animations[animationIndex];
  26679. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26680. }
  26681. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26682. }
  26683. }
  26684. }
  26685. return mesh;
  26686. };
  26687. /**
  26688. * Creates a ribbon mesh.
  26689. * Please consider using the same method from the MeshBuilder class instead.
  26690. * 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.
  26691. *
  26692. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26693. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26694. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26695. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26696. * 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.
  26697. * 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.
  26698. * 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
  26699. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26700. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26702. */
  26703. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26704. if (closeArray === void 0) { closeArray = false; }
  26705. if (updatable === void 0) { updatable = false; }
  26706. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26707. pathArray: pathArray,
  26708. closeArray: closeArray,
  26709. closePath: closePath,
  26710. offset: offset,
  26711. updatable: updatable,
  26712. sideOrientation: sideOrientation,
  26713. instance: instance
  26714. }, scene);
  26715. };
  26716. /**
  26717. * Creates a plane polygonal mesh. By default, this is a disc.
  26718. * Please consider using the same method from the MeshBuilder class instead.
  26719. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26720. * 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.
  26721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26724. */
  26725. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26726. if (scene === void 0) { scene = null; }
  26727. var options = {
  26728. radius: radius,
  26729. tessellation: tessellation,
  26730. sideOrientation: sideOrientation,
  26731. updatable: updatable
  26732. };
  26733. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  26734. };
  26735. /**
  26736. * Creates a box mesh.
  26737. * Please consider using the same method from the MeshBuilder class instead.
  26738. * The parameter `size` sets the size (float) of each box side (default 1).
  26739. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26740. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26742. */
  26743. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  26744. if (scene === void 0) { scene = null; }
  26745. var options = {
  26746. size: size,
  26747. sideOrientation: sideOrientation,
  26748. updatable: updatable
  26749. };
  26750. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  26751. };
  26752. /**
  26753. * Creates a sphere mesh.
  26754. * Please consider using the same method from the MeshBuilder class instead.
  26755. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26756. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26758. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26760. */
  26761. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  26762. var options = {
  26763. segments: segments,
  26764. diameterX: diameter,
  26765. diameterY: diameter,
  26766. diameterZ: diameter,
  26767. sideOrientation: sideOrientation,
  26768. updatable: updatable
  26769. };
  26770. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  26771. };
  26772. /**
  26773. * Creates a cylinder or a cone mesh.
  26774. * Please consider using the same method from the MeshBuilder class instead.
  26775. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26776. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26777. * 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.
  26778. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26779. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26781. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26783. */
  26784. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  26785. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  26786. if (scene !== undefined) {
  26787. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  26788. updatable = scene;
  26789. }
  26790. scene = subdivisions;
  26791. subdivisions = 1;
  26792. }
  26793. var options = {
  26794. height: height,
  26795. diameterTop: diameterTop,
  26796. diameterBottom: diameterBottom,
  26797. tessellation: tessellation,
  26798. subdivisions: subdivisions,
  26799. sideOrientation: sideOrientation,
  26800. updatable: updatable
  26801. };
  26802. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  26803. };
  26804. // Torus (Code from SharpDX.org)
  26805. /**
  26806. * Creates a torus mesh.
  26807. * Please consider using the same method from the MeshBuilder class instead.
  26808. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26809. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26810. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26812. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26814. */
  26815. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  26816. var options = {
  26817. diameter: diameter,
  26818. thickness: thickness,
  26819. tessellation: tessellation,
  26820. sideOrientation: sideOrientation,
  26821. updatable: updatable
  26822. };
  26823. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  26824. };
  26825. /**
  26826. * Creates a torus knot mesh.
  26827. * Please consider using the same method from the MeshBuilder class instead.
  26828. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26829. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26830. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26831. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26835. */
  26836. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  26837. var options = {
  26838. radius: radius,
  26839. tube: tube,
  26840. radialSegments: radialSegments,
  26841. tubularSegments: tubularSegments,
  26842. p: p,
  26843. q: q,
  26844. sideOrientation: sideOrientation,
  26845. updatable: updatable
  26846. };
  26847. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  26848. };
  26849. /**
  26850. * Creates a line mesh.
  26851. * Please consider using the same method from the MeshBuilder class instead.
  26852. * 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.
  26853. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26854. * The parameter `points` is an array successive Vector3.
  26855. * 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
  26856. * When updating an instance, remember that only point positions can change, not the number of points.
  26857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26858. */
  26859. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  26860. if (scene === void 0) { scene = null; }
  26861. if (updatable === void 0) { updatable = false; }
  26862. if (instance === void 0) { instance = null; }
  26863. var options = {
  26864. points: points,
  26865. updatable: updatable,
  26866. instance: instance
  26867. };
  26868. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  26869. };
  26870. /**
  26871. * Creates a dashed line mesh.
  26872. * Please consider using the same method from the MeshBuilder class instead.
  26873. * 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.
  26874. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26875. * The parameter `points` is an array successive Vector3.
  26876. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26877. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26878. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26879. * 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
  26880. * When updating an instance, remember that only point positions can change, not the number of points.
  26881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26882. */
  26883. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  26884. if (scene === void 0) { scene = null; }
  26885. var options = {
  26886. points: points,
  26887. dashSize: dashSize,
  26888. gapSize: gapSize,
  26889. dashNb: dashNb,
  26890. updatable: updatable,
  26891. instance: instance
  26892. };
  26893. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26894. };
  26895. /**
  26896. * Creates a polygon mesh.
  26897. * Please consider using the same method from the MeshBuilder class instead.
  26898. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  26899. * 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.
  26900. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26902. * Remember you can only change the shape positions, not their number when updating a polygon.
  26903. */
  26904. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  26905. var options = {
  26906. shape: shape,
  26907. holes: holes,
  26908. updatable: updatable,
  26909. sideOrientation: sideOrientation
  26910. };
  26911. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  26912. };
  26913. /**
  26914. * Creates an extruded polygon mesh, with depth in the Y direction.
  26915. * Please consider using the same method from the MeshBuilder class instead.
  26916. */
  26917. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  26918. var options = {
  26919. shape: shape,
  26920. holes: holes,
  26921. depth: depth,
  26922. updatable: updatable,
  26923. sideOrientation: sideOrientation
  26924. };
  26925. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  26926. };
  26927. /**
  26928. * Creates an extruded shape mesh.
  26929. * 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.
  26930. * Please consider using the same method from the MeshBuilder class instead.
  26931. *
  26932. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26933. * 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
  26934. * extruded along the Z axis.
  26935. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26936. * 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.
  26937. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26938. * 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
  26939. * 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
  26940. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26944. */
  26945. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26946. if (scene === void 0) { scene = null; }
  26947. var options = {
  26948. shape: shape,
  26949. path: path,
  26950. scale: scale,
  26951. rotation: rotation,
  26952. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26953. sideOrientation: sideOrientation,
  26954. instance: instance,
  26955. updatable: updatable
  26956. };
  26957. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26958. };
  26959. /**
  26960. * Creates an custom extruded shape mesh.
  26961. * 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.
  26962. * Please consider using the same method from the MeshBuilder class instead.
  26963. *
  26964. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26965. * 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
  26966. * extruded along the Z axis.
  26967. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26968. * 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
  26969. * and the distance of this point from the begining of the path :
  26970. * ```javascript
  26971. * var rotationFunction = function(i, distance) {
  26972. * // do things
  26973. * return rotationValue; }
  26974. * ```
  26975. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26976. * 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
  26977. * and the distance of this point from the begining of the path :
  26978. * ```javascript
  26979. * var scaleFunction = function(i, distance) {
  26980. * // do things
  26981. * return scaleValue;}
  26982. * ```
  26983. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26984. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26985. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26986. * 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
  26987. * 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
  26988. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26989. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26990. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26992. */
  26993. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26994. var options = {
  26995. shape: shape,
  26996. path: path,
  26997. scaleFunction: scaleFunction,
  26998. rotationFunction: rotationFunction,
  26999. ribbonCloseArray: ribbonCloseArray,
  27000. ribbonClosePath: ribbonClosePath,
  27001. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27002. sideOrientation: sideOrientation,
  27003. instance: instance,
  27004. updatable: updatable
  27005. };
  27006. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27007. };
  27008. /**
  27009. * Creates lathe mesh.
  27010. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27011. * Please consider using the same method from the MeshBuilder class instead.
  27012. * 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
  27013. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27014. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27015. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27017. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27019. */
  27020. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27021. var options = {
  27022. shape: shape,
  27023. radius: radius,
  27024. tessellation: tessellation,
  27025. sideOrientation: sideOrientation,
  27026. updatable: updatable
  27027. };
  27028. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27029. };
  27030. /**
  27031. * Creates a plane mesh.
  27032. * Please consider using the same method from the MeshBuilder class instead.
  27033. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27037. */
  27038. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27039. var options = {
  27040. size: size,
  27041. width: size,
  27042. height: size,
  27043. sideOrientation: sideOrientation,
  27044. updatable: updatable
  27045. };
  27046. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27047. };
  27048. /**
  27049. * Creates a ground mesh.
  27050. * Please consider using the same method from the MeshBuilder class instead.
  27051. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27052. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27054. */
  27055. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27056. var options = {
  27057. width: width,
  27058. height: height,
  27059. subdivisions: subdivisions,
  27060. updatable: updatable
  27061. };
  27062. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27063. };
  27064. /**
  27065. * Creates a tiled ground mesh.
  27066. * Please consider using the same method from the MeshBuilder class instead.
  27067. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27068. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27069. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27070. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27071. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27072. * numbers of subdivisions on the ground width and height of each tile.
  27073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27074. */
  27075. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27076. var options = {
  27077. xmin: xmin,
  27078. zmin: zmin,
  27079. xmax: xmax,
  27080. zmax: zmax,
  27081. subdivisions: subdivisions,
  27082. precision: precision,
  27083. updatable: updatable
  27084. };
  27085. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27086. };
  27087. /**
  27088. * Creates a ground mesh from a height map.
  27089. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27090. * Please consider using the same method from the MeshBuilder class instead.
  27091. * The parameter `url` sets the URL of the height map image resource.
  27092. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27093. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27094. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27095. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27096. * 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).
  27097. * This function is passed the newly built mesh :
  27098. * ```javascript
  27099. * function(mesh) { // do things
  27100. * return; }
  27101. * ```
  27102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27103. */
  27104. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27105. var options = {
  27106. width: width,
  27107. height: height,
  27108. subdivisions: subdivisions,
  27109. minHeight: minHeight,
  27110. maxHeight: maxHeight,
  27111. updatable: updatable,
  27112. onReady: onReady
  27113. };
  27114. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27115. };
  27116. /**
  27117. * Creates a tube mesh.
  27118. * 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.
  27119. * Please consider using the same method from the MeshBuilder class instead.
  27120. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27121. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27122. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27123. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27124. * 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.
  27125. * It must return a radius value (positive float) :
  27126. * ```javascript
  27127. * var radiusFunction = function(i, distance) {
  27128. * // do things
  27129. * return radius; }
  27130. * ```
  27131. * 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
  27132. * 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
  27133. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27134. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27136. */
  27137. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27138. var options = {
  27139. path: path,
  27140. radius: radius,
  27141. tessellation: tessellation,
  27142. radiusFunction: radiusFunction,
  27143. arc: 1,
  27144. cap: cap,
  27145. updatable: updatable,
  27146. sideOrientation: sideOrientation,
  27147. instance: instance
  27148. };
  27149. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27150. };
  27151. /**
  27152. * Creates a polyhedron mesh.
  27153. * Please consider using the same method from the MeshBuilder class instead.
  27154. * 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
  27155. * to choose the wanted type.
  27156. * The parameter `size` (positive float, default 1) sets the polygon size.
  27157. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27158. * 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`.
  27159. * 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
  27160. * 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)`).
  27161. * 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
  27162. * 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.
  27163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27166. */
  27167. Mesh.CreatePolyhedron = function (name, options, scene) {
  27168. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27169. };
  27170. /**
  27171. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27172. * Please consider using the same method from the MeshBuilder class instead.
  27173. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27174. * 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`).
  27175. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27176. * 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.
  27177. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27178. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27180. */
  27181. Mesh.CreateIcoSphere = function (name, options, scene) {
  27182. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27183. };
  27184. /**
  27185. * Creates a decal mesh.
  27186. * Please consider using the same method from the MeshBuilder class instead.
  27187. * 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.
  27188. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27189. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27190. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27191. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27192. */
  27193. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27194. var options = {
  27195. position: position,
  27196. normal: normal,
  27197. size: size,
  27198. angle: angle
  27199. };
  27200. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27201. };
  27202. // Skeletons
  27203. /**
  27204. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27205. */
  27206. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27207. if (!this._sourcePositions) {
  27208. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27209. if (!source) {
  27210. return this._sourcePositions;
  27211. }
  27212. this._sourcePositions = new Float32Array(source);
  27213. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27214. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27215. }
  27216. }
  27217. return this._sourcePositions;
  27218. };
  27219. /**
  27220. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27221. */
  27222. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27223. if (!this._sourceNormals) {
  27224. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27225. if (!source) {
  27226. return this._sourceNormals;
  27227. }
  27228. this._sourceNormals = new Float32Array(source);
  27229. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27230. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27231. }
  27232. }
  27233. return this._sourceNormals;
  27234. };
  27235. /**
  27236. * Updates the vertex buffer by applying transformation from the bones.
  27237. * Returns the Mesh.
  27238. *
  27239. * @param {skeleton} skeleton to apply
  27240. */
  27241. Mesh.prototype.applySkeleton = function (skeleton) {
  27242. if (!this.geometry) {
  27243. return this;
  27244. }
  27245. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27246. return this;
  27247. }
  27248. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27249. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27250. return this;
  27251. }
  27252. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27253. return this;
  27254. }
  27255. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27256. return this;
  27257. }
  27258. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27259. return this;
  27260. }
  27261. if (!this._sourcePositions) {
  27262. var submeshes = this.subMeshes.slice();
  27263. this.setPositionsForCPUSkinning();
  27264. this.subMeshes = submeshes;
  27265. }
  27266. if (!this._sourceNormals) {
  27267. this.setNormalsForCPUSkinning();
  27268. }
  27269. // positionsData checks for not being Float32Array will only pass at most once
  27270. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27271. if (!positionsData) {
  27272. return this;
  27273. }
  27274. if (!(positionsData instanceof Float32Array)) {
  27275. positionsData = new Float32Array(positionsData);
  27276. }
  27277. // normalsData checks for not being Float32Array will only pass at most once
  27278. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27279. if (!normalsData) {
  27280. return this;
  27281. }
  27282. if (!(normalsData instanceof Float32Array)) {
  27283. normalsData = new Float32Array(normalsData);
  27284. }
  27285. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27286. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27287. if (!matricesWeightsData || !matricesIndicesData) {
  27288. return this;
  27289. }
  27290. var needExtras = this.numBoneInfluencers > 4;
  27291. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27292. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27293. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27294. var tempVector3 = BABYLON.Vector3.Zero();
  27295. var finalMatrix = new BABYLON.Matrix();
  27296. var tempMatrix = new BABYLON.Matrix();
  27297. var matWeightIdx = 0;
  27298. var inf;
  27299. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27300. var weight;
  27301. for (inf = 0; inf < 4; inf++) {
  27302. weight = matricesWeightsData[matWeightIdx + inf];
  27303. if (weight > 0) {
  27304. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27305. finalMatrix.addToSelf(tempMatrix);
  27306. }
  27307. else
  27308. break;
  27309. }
  27310. if (needExtras) {
  27311. for (inf = 0; inf < 4; inf++) {
  27312. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27313. if (weight > 0) {
  27314. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27315. finalMatrix.addToSelf(tempMatrix);
  27316. }
  27317. else
  27318. break;
  27319. }
  27320. }
  27321. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27322. tempVector3.toArray(positionsData, index);
  27323. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27324. tempVector3.toArray(normalsData, index);
  27325. finalMatrix.reset();
  27326. }
  27327. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27328. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27329. return this;
  27330. };
  27331. // Tools
  27332. /**
  27333. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27334. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27335. */
  27336. Mesh.MinMax = function (meshes) {
  27337. var minVector = null;
  27338. var maxVector = null;
  27339. meshes.forEach(function (mesh, index, array) {
  27340. var boundingInfo = mesh.getBoundingInfo();
  27341. var boundingBox = boundingInfo.boundingBox;
  27342. if (!minVector || !maxVector) {
  27343. minVector = boundingBox.minimumWorld;
  27344. maxVector = boundingBox.maximumWorld;
  27345. }
  27346. else {
  27347. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27348. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27349. }
  27350. });
  27351. if (!minVector || !maxVector) {
  27352. return {
  27353. min: BABYLON.Vector3.Zero(),
  27354. max: BABYLON.Vector3.Zero()
  27355. };
  27356. }
  27357. return {
  27358. min: minVector,
  27359. max: maxVector
  27360. };
  27361. };
  27362. /**
  27363. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27364. */
  27365. Mesh.Center = function (meshesOrMinMaxVector) {
  27366. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27367. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27368. };
  27369. /**
  27370. * Merge the array of meshes into a single mesh for performance reasons.
  27371. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27372. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27373. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27374. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27375. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27376. */
  27377. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27378. if (disposeSource === void 0) { disposeSource = true; }
  27379. var index;
  27380. if (!allow32BitsIndices) {
  27381. var totalVertices = 0;
  27382. // Counting vertices
  27383. for (index = 0; index < meshes.length; index++) {
  27384. if (meshes[index]) {
  27385. totalVertices += meshes[index].getTotalVertices();
  27386. if (totalVertices > 65536) {
  27387. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27388. return null;
  27389. }
  27390. }
  27391. }
  27392. }
  27393. // Merge
  27394. var vertexData = null;
  27395. var otherVertexData;
  27396. var indiceArray = new Array();
  27397. var source = null;
  27398. for (index = 0; index < meshes.length; index++) {
  27399. if (meshes[index]) {
  27400. meshes[index].computeWorldMatrix(true);
  27401. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27402. otherVertexData.transform(meshes[index].getWorldMatrix());
  27403. if (vertexData) {
  27404. vertexData.merge(otherVertexData);
  27405. }
  27406. else {
  27407. vertexData = otherVertexData;
  27408. source = meshes[index];
  27409. }
  27410. if (subdivideWithSubMeshes) {
  27411. indiceArray.push(meshes[index].getTotalIndices());
  27412. }
  27413. }
  27414. }
  27415. source = source;
  27416. if (!meshSubclass) {
  27417. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27418. }
  27419. vertexData.applyToMesh(meshSubclass);
  27420. // Setting properties
  27421. meshSubclass.material = source.material;
  27422. meshSubclass.checkCollisions = source.checkCollisions;
  27423. // Cleaning
  27424. if (disposeSource) {
  27425. for (index = 0; index < meshes.length; index++) {
  27426. if (meshes[index]) {
  27427. meshes[index].dispose();
  27428. }
  27429. }
  27430. }
  27431. // Subdivide
  27432. if (subdivideWithSubMeshes) {
  27433. //-- Suppresions du submesh global
  27434. meshSubclass.releaseSubMeshes();
  27435. index = 0;
  27436. var offset = 0;
  27437. //-- aplique la subdivision en fonction du tableau d'indices
  27438. while (index < indiceArray.length) {
  27439. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27440. offset += indiceArray[index];
  27441. index++;
  27442. }
  27443. }
  27444. return meshSubclass;
  27445. };
  27446. // Consts
  27447. Mesh._FRONTSIDE = 0;
  27448. Mesh._BACKSIDE = 1;
  27449. Mesh._DOUBLESIDE = 2;
  27450. Mesh._DEFAULTSIDE = 0;
  27451. Mesh._NO_CAP = 0;
  27452. Mesh._CAP_START = 1;
  27453. Mesh._CAP_END = 2;
  27454. Mesh._CAP_ALL = 3;
  27455. return Mesh;
  27456. }(BABYLON.AbstractMesh));
  27457. BABYLON.Mesh = Mesh;
  27458. })(BABYLON || (BABYLON = {}));
  27459. //# sourceMappingURL=babylon.mesh.js.map
  27460. var BABYLON;
  27461. (function (BABYLON) {
  27462. var BaseSubMesh = /** @class */ (function () {
  27463. function BaseSubMesh() {
  27464. }
  27465. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27466. get: function () {
  27467. return this._materialEffect;
  27468. },
  27469. enumerable: true,
  27470. configurable: true
  27471. });
  27472. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27473. if (defines === void 0) { defines = null; }
  27474. if (this._materialEffect === effect) {
  27475. if (!effect) {
  27476. this._materialDefines = null;
  27477. }
  27478. return;
  27479. }
  27480. this._materialDefines = defines;
  27481. this._materialEffect = effect;
  27482. };
  27483. return BaseSubMesh;
  27484. }());
  27485. BABYLON.BaseSubMesh = BaseSubMesh;
  27486. var SubMesh = /** @class */ (function (_super) {
  27487. __extends(SubMesh, _super);
  27488. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27489. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27490. var _this = _super.call(this) || this;
  27491. _this.materialIndex = materialIndex;
  27492. _this.verticesStart = verticesStart;
  27493. _this.verticesCount = verticesCount;
  27494. _this.indexStart = indexStart;
  27495. _this.indexCount = indexCount;
  27496. _this._renderId = 0;
  27497. _this._mesh = mesh;
  27498. _this._renderingMesh = renderingMesh || mesh;
  27499. mesh.subMeshes.push(_this);
  27500. _this._trianglePlanes = [];
  27501. _this._id = mesh.subMeshes.length - 1;
  27502. if (createBoundingBox) {
  27503. _this.refreshBoundingInfo();
  27504. mesh.computeWorldMatrix(true);
  27505. }
  27506. return _this;
  27507. }
  27508. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27509. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27510. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27511. };
  27512. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27513. get: function () {
  27514. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27515. },
  27516. enumerable: true,
  27517. configurable: true
  27518. });
  27519. /**
  27520. * Returns the submesh BoudingInfo object.
  27521. */
  27522. SubMesh.prototype.getBoundingInfo = function () {
  27523. if (this.IsGlobal) {
  27524. return this._mesh.getBoundingInfo();
  27525. }
  27526. return this._boundingInfo;
  27527. };
  27528. /**
  27529. * Sets the submesh BoundingInfo.
  27530. * Return the SubMesh.
  27531. */
  27532. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27533. this._boundingInfo = boundingInfo;
  27534. return this;
  27535. };
  27536. /**
  27537. * Returns the mesh of the current submesh.
  27538. */
  27539. SubMesh.prototype.getMesh = function () {
  27540. return this._mesh;
  27541. };
  27542. /**
  27543. * Returns the rendering mesh of the submesh.
  27544. */
  27545. SubMesh.prototype.getRenderingMesh = function () {
  27546. return this._renderingMesh;
  27547. };
  27548. /**
  27549. * Returns the submesh material.
  27550. */
  27551. SubMesh.prototype.getMaterial = function () {
  27552. var rootMaterial = this._renderingMesh.material;
  27553. if (rootMaterial === null || rootMaterial === undefined) {
  27554. return this._mesh.getScene().defaultMaterial;
  27555. }
  27556. else if (rootMaterial.getSubMaterial) {
  27557. var multiMaterial = rootMaterial;
  27558. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27559. if (this._currentMaterial !== effectiveMaterial) {
  27560. this._currentMaterial = effectiveMaterial;
  27561. this._materialDefines = null;
  27562. }
  27563. return effectiveMaterial;
  27564. }
  27565. return rootMaterial;
  27566. };
  27567. // Methods
  27568. /**
  27569. * Sets a new updated BoundingInfo object to the submesh.
  27570. * Returns the SubMesh.
  27571. */
  27572. SubMesh.prototype.refreshBoundingInfo = function () {
  27573. this._lastColliderWorldVertices = null;
  27574. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27575. return this;
  27576. }
  27577. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27578. if (!data) {
  27579. this._boundingInfo = this._mesh.getBoundingInfo();
  27580. return this;
  27581. }
  27582. var indices = this._renderingMesh.getIndices();
  27583. var extend;
  27584. //is this the only submesh?
  27585. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27586. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27587. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27588. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27589. }
  27590. else {
  27591. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27592. }
  27593. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27594. return this;
  27595. };
  27596. SubMesh.prototype._checkCollision = function (collider) {
  27597. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27598. return boundingInfo._checkCollision(collider);
  27599. };
  27600. /**
  27601. * Updates the submesh BoundingInfo.
  27602. * Returns the Submesh.
  27603. */
  27604. SubMesh.prototype.updateBoundingInfo = function (world) {
  27605. var boundingInfo = this.getBoundingInfo();
  27606. if (!boundingInfo) {
  27607. this.refreshBoundingInfo();
  27608. boundingInfo = this.getBoundingInfo();
  27609. }
  27610. boundingInfo.update(world);
  27611. return this;
  27612. };
  27613. /**
  27614. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27615. * Boolean returned.
  27616. */
  27617. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27618. var boundingInfo = this.getBoundingInfo();
  27619. if (!boundingInfo) {
  27620. return false;
  27621. }
  27622. return boundingInfo.isInFrustum(frustumPlanes);
  27623. };
  27624. /**
  27625. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27626. * Boolean returned.
  27627. */
  27628. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27629. var boundingInfo = this.getBoundingInfo();
  27630. if (!boundingInfo) {
  27631. return false;
  27632. }
  27633. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27634. };
  27635. /**
  27636. * Renders the submesh.
  27637. * Returns it.
  27638. */
  27639. SubMesh.prototype.render = function (enableAlphaMode) {
  27640. this._renderingMesh.render(this, enableAlphaMode);
  27641. return this;
  27642. };
  27643. /**
  27644. * Returns a new Index Buffer.
  27645. * Type returned : WebGLBuffer.
  27646. */
  27647. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27648. if (!this._linesIndexBuffer) {
  27649. var linesIndices = [];
  27650. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27651. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27652. }
  27653. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27654. this.linesIndexCount = linesIndices.length;
  27655. }
  27656. return this._linesIndexBuffer;
  27657. };
  27658. /**
  27659. * True is the passed Ray intersects the submesh bounding box.
  27660. * Boolean returned.
  27661. */
  27662. SubMesh.prototype.canIntersects = function (ray) {
  27663. var boundingInfo = this.getBoundingInfo();
  27664. if (!boundingInfo) {
  27665. return false;
  27666. }
  27667. return ray.intersectsBox(boundingInfo.boundingBox);
  27668. };
  27669. /**
  27670. * Returns an object IntersectionInfo.
  27671. */
  27672. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27673. var intersectInfo = null;
  27674. // LineMesh first as it's also a Mesh...
  27675. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27676. var lineMesh = this._mesh;
  27677. // Line test
  27678. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27679. var p0 = positions[indices[index]];
  27680. var p1 = positions[indices[index + 1]];
  27681. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27682. if (length < 0) {
  27683. continue;
  27684. }
  27685. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27686. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27687. if (fastCheck) {
  27688. break;
  27689. }
  27690. }
  27691. }
  27692. }
  27693. else {
  27694. // Triangles test
  27695. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27696. var p0 = positions[indices[index]];
  27697. var p1 = positions[indices[index + 1]];
  27698. var p2 = positions[indices[index + 2]];
  27699. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27700. if (currentIntersectInfo) {
  27701. if (currentIntersectInfo.distance < 0) {
  27702. continue;
  27703. }
  27704. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27705. intersectInfo = currentIntersectInfo;
  27706. intersectInfo.faceId = index / 3;
  27707. if (fastCheck) {
  27708. break;
  27709. }
  27710. }
  27711. }
  27712. }
  27713. }
  27714. return intersectInfo;
  27715. };
  27716. SubMesh.prototype._rebuild = function () {
  27717. if (this._linesIndexBuffer) {
  27718. this._linesIndexBuffer = null;
  27719. }
  27720. };
  27721. // Clone
  27722. /**
  27723. * Creates a new Submesh from the passed Mesh.
  27724. */
  27725. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27726. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27727. if (!this.IsGlobal) {
  27728. var boundingInfo = this.getBoundingInfo();
  27729. if (!boundingInfo) {
  27730. return result;
  27731. }
  27732. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  27733. }
  27734. return result;
  27735. };
  27736. // Dispose
  27737. /**
  27738. * Disposes the Submesh.
  27739. * Returns nothing.
  27740. */
  27741. SubMesh.prototype.dispose = function () {
  27742. if (this._linesIndexBuffer) {
  27743. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  27744. this._linesIndexBuffer = null;
  27745. }
  27746. // Remove from mesh
  27747. var index = this._mesh.subMeshes.indexOf(this);
  27748. this._mesh.subMeshes.splice(index, 1);
  27749. };
  27750. // Statics
  27751. /**
  27752. * Creates a new Submesh from the passed parameters :
  27753. * - materialIndex (integer) : the index of the main mesh material.
  27754. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  27755. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  27756. * - mesh (Mesh) : the main mesh to create the submesh from.
  27757. * - renderingMesh (optional Mesh) : rendering mesh.
  27758. */
  27759. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  27760. var minVertexIndex = Number.MAX_VALUE;
  27761. var maxVertexIndex = -Number.MAX_VALUE;
  27762. renderingMesh = (renderingMesh || mesh);
  27763. var indices = renderingMesh.getIndices();
  27764. for (var index = startIndex; index < startIndex + indexCount; index++) {
  27765. var vertexIndex = indices[index];
  27766. if (vertexIndex < minVertexIndex)
  27767. minVertexIndex = vertexIndex;
  27768. if (vertexIndex > maxVertexIndex)
  27769. maxVertexIndex = vertexIndex;
  27770. }
  27771. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  27772. };
  27773. return SubMesh;
  27774. }(BaseSubMesh));
  27775. BABYLON.SubMesh = SubMesh;
  27776. })(BABYLON || (BABYLON = {}));
  27777. //# sourceMappingURL=babylon.subMesh.js.map
  27778. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27779. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27780. s = arguments[i];
  27781. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27782. t[p] = s[p];
  27783. }
  27784. return t;
  27785. };
  27786. var BABYLON;
  27787. (function (BABYLON) {
  27788. var MaterialDefines = /** @class */ (function () {
  27789. function MaterialDefines() {
  27790. this._isDirty = true;
  27791. this._areLightsDirty = true;
  27792. this._areAttributesDirty = true;
  27793. this._areTexturesDirty = true;
  27794. this._areFresnelDirty = true;
  27795. this._areMiscDirty = true;
  27796. this._areImageProcessingDirty = true;
  27797. this._normals = false;
  27798. this._uvs = false;
  27799. this._needNormals = false;
  27800. this._needUVs = false;
  27801. }
  27802. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27803. get: function () {
  27804. return this._isDirty;
  27805. },
  27806. enumerable: true,
  27807. configurable: true
  27808. });
  27809. MaterialDefines.prototype.markAsProcessed = function () {
  27810. this._isDirty = false;
  27811. this._areAttributesDirty = false;
  27812. this._areTexturesDirty = false;
  27813. this._areFresnelDirty = false;
  27814. this._areLightsDirty = false;
  27815. this._areMiscDirty = false;
  27816. this._areImageProcessingDirty = false;
  27817. };
  27818. MaterialDefines.prototype.markAsUnprocessed = function () {
  27819. this._isDirty = true;
  27820. };
  27821. MaterialDefines.prototype.markAllAsDirty = function () {
  27822. this._areTexturesDirty = true;
  27823. this._areAttributesDirty = true;
  27824. this._areLightsDirty = true;
  27825. this._areFresnelDirty = true;
  27826. this._areMiscDirty = true;
  27827. this._areImageProcessingDirty = true;
  27828. this._isDirty = true;
  27829. };
  27830. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27831. this._areImageProcessingDirty = true;
  27832. this._isDirty = true;
  27833. };
  27834. MaterialDefines.prototype.markAsLightDirty = function () {
  27835. this._areLightsDirty = true;
  27836. this._isDirty = true;
  27837. };
  27838. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27839. this._areAttributesDirty = true;
  27840. this._isDirty = true;
  27841. };
  27842. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27843. this._areTexturesDirty = true;
  27844. this._isDirty = true;
  27845. };
  27846. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27847. this._areFresnelDirty = true;
  27848. this._isDirty = true;
  27849. };
  27850. MaterialDefines.prototype.markAsMiscDirty = function () {
  27851. this._areMiscDirty = true;
  27852. this._isDirty = true;
  27853. };
  27854. MaterialDefines.prototype.rebuild = function () {
  27855. if (this._keys) {
  27856. delete this._keys;
  27857. }
  27858. this._keys = [];
  27859. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27860. var key = _a[_i];
  27861. if (key[0] === "_") {
  27862. continue;
  27863. }
  27864. this._keys.push(key);
  27865. }
  27866. };
  27867. MaterialDefines.prototype.isEqual = function (other) {
  27868. if (this._keys.length !== other._keys.length) {
  27869. return false;
  27870. }
  27871. for (var index = 0; index < this._keys.length; index++) {
  27872. var prop = this._keys[index];
  27873. if (this[prop] !== other[prop]) {
  27874. return false;
  27875. }
  27876. }
  27877. return true;
  27878. };
  27879. MaterialDefines.prototype.cloneTo = function (other) {
  27880. if (this._keys.length !== other._keys.length) {
  27881. other._keys = this._keys.slice(0);
  27882. }
  27883. for (var index = 0; index < this._keys.length; index++) {
  27884. var prop = this._keys[index];
  27885. other[prop] = this[prop];
  27886. }
  27887. };
  27888. MaterialDefines.prototype.reset = function () {
  27889. for (var index = 0; index < this._keys.length; index++) {
  27890. var prop = this._keys[index];
  27891. if (typeof (this[prop]) === "number") {
  27892. this[prop] = 0;
  27893. }
  27894. else {
  27895. this[prop] = false;
  27896. }
  27897. }
  27898. };
  27899. MaterialDefines.prototype.toString = function () {
  27900. var result = "";
  27901. for (var index = 0; index < this._keys.length; index++) {
  27902. var prop = this._keys[index];
  27903. var value = this[prop];
  27904. if (typeof (value) === "number") {
  27905. result += "#define " + prop + " " + this[prop] + "\n";
  27906. }
  27907. else if (value) {
  27908. result += "#define " + prop + "\n";
  27909. }
  27910. }
  27911. return result;
  27912. };
  27913. return MaterialDefines;
  27914. }());
  27915. BABYLON.MaterialDefines = MaterialDefines;
  27916. var Material = /** @class */ (function () {
  27917. function Material(name, scene, doNotAdd) {
  27918. this.checkReadyOnEveryCall = false;
  27919. this.checkReadyOnlyOnce = false;
  27920. this.state = "";
  27921. this.alpha = 1.0;
  27922. this._backFaceCulling = true;
  27923. this.doNotSerialize = false;
  27924. this.storeEffectOnSubMeshes = false;
  27925. /**
  27926. * An event triggered when the material is disposed.
  27927. * @type {BABYLON.Observable}
  27928. */
  27929. this.onDisposeObservable = new BABYLON.Observable();
  27930. /**
  27931. * An event triggered when the material is bound.
  27932. * @type {BABYLON.Observable}
  27933. */
  27934. this.onBindObservable = new BABYLON.Observable();
  27935. /**
  27936. * An event triggered when the material is unbound.
  27937. * @type {BABYLON.Observable}
  27938. */
  27939. this.onUnBindObservable = new BABYLON.Observable();
  27940. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27941. this._needDepthPrePass = false;
  27942. this.disableDepthWrite = false;
  27943. this.forceDepthWrite = false;
  27944. this.separateCullingPass = false;
  27945. this._fogEnabled = true;
  27946. this.pointSize = 1.0;
  27947. this.zOffset = 0;
  27948. this._wasPreviouslyReady = false;
  27949. this._fillMode = Material.TriangleFillMode;
  27950. this.name = name;
  27951. this.id = name || BABYLON.Tools.RandomId();
  27952. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27953. if (this._scene.useRightHandedSystem) {
  27954. this.sideOrientation = Material.ClockWiseSideOrientation;
  27955. }
  27956. else {
  27957. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27958. }
  27959. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27960. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27961. if (!doNotAdd) {
  27962. this._scene.materials.push(this);
  27963. }
  27964. }
  27965. Object.defineProperty(Material, "TriangleFillMode", {
  27966. get: function () {
  27967. return Material._TriangleFillMode;
  27968. },
  27969. enumerable: true,
  27970. configurable: true
  27971. });
  27972. Object.defineProperty(Material, "WireFrameFillMode", {
  27973. get: function () {
  27974. return Material._WireFrameFillMode;
  27975. },
  27976. enumerable: true,
  27977. configurable: true
  27978. });
  27979. Object.defineProperty(Material, "PointFillMode", {
  27980. get: function () {
  27981. return Material._PointFillMode;
  27982. },
  27983. enumerable: true,
  27984. configurable: true
  27985. });
  27986. Object.defineProperty(Material, "PointListDrawMode", {
  27987. get: function () {
  27988. return Material._PointListDrawMode;
  27989. },
  27990. enumerable: true,
  27991. configurable: true
  27992. });
  27993. Object.defineProperty(Material, "LineListDrawMode", {
  27994. get: function () {
  27995. return Material._LineListDrawMode;
  27996. },
  27997. enumerable: true,
  27998. configurable: true
  27999. });
  28000. Object.defineProperty(Material, "LineLoopDrawMode", {
  28001. get: function () {
  28002. return Material._LineLoopDrawMode;
  28003. },
  28004. enumerable: true,
  28005. configurable: true
  28006. });
  28007. Object.defineProperty(Material, "LineStripDrawMode", {
  28008. get: function () {
  28009. return Material._LineStripDrawMode;
  28010. },
  28011. enumerable: true,
  28012. configurable: true
  28013. });
  28014. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28015. get: function () {
  28016. return Material._TriangleStripDrawMode;
  28017. },
  28018. enumerable: true,
  28019. configurable: true
  28020. });
  28021. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28022. get: function () {
  28023. return Material._TriangleFanDrawMode;
  28024. },
  28025. enumerable: true,
  28026. configurable: true
  28027. });
  28028. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28029. get: function () {
  28030. return Material._ClockWiseSideOrientation;
  28031. },
  28032. enumerable: true,
  28033. configurable: true
  28034. });
  28035. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28036. get: function () {
  28037. return Material._CounterClockWiseSideOrientation;
  28038. },
  28039. enumerable: true,
  28040. configurable: true
  28041. });
  28042. Object.defineProperty(Material, "TextureDirtyFlag", {
  28043. get: function () {
  28044. return Material._TextureDirtyFlag;
  28045. },
  28046. enumerable: true,
  28047. configurable: true
  28048. });
  28049. Object.defineProperty(Material, "LightDirtyFlag", {
  28050. get: function () {
  28051. return Material._LightDirtyFlag;
  28052. },
  28053. enumerable: true,
  28054. configurable: true
  28055. });
  28056. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28057. get: function () {
  28058. return Material._FresnelDirtyFlag;
  28059. },
  28060. enumerable: true,
  28061. configurable: true
  28062. });
  28063. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28064. get: function () {
  28065. return Material._AttributesDirtyFlag;
  28066. },
  28067. enumerable: true,
  28068. configurable: true
  28069. });
  28070. Object.defineProperty(Material, "MiscDirtyFlag", {
  28071. get: function () {
  28072. return Material._MiscDirtyFlag;
  28073. },
  28074. enumerable: true,
  28075. configurable: true
  28076. });
  28077. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28078. get: function () {
  28079. return this._backFaceCulling;
  28080. },
  28081. set: function (value) {
  28082. if (this._backFaceCulling === value) {
  28083. return;
  28084. }
  28085. this._backFaceCulling = value;
  28086. this.markAsDirty(Material.TextureDirtyFlag);
  28087. },
  28088. enumerable: true,
  28089. configurable: true
  28090. });
  28091. Object.defineProperty(Material.prototype, "onDispose", {
  28092. set: function (callback) {
  28093. if (this._onDisposeObserver) {
  28094. this.onDisposeObservable.remove(this._onDisposeObserver);
  28095. }
  28096. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28097. },
  28098. enumerable: true,
  28099. configurable: true
  28100. });
  28101. Object.defineProperty(Material.prototype, "onBind", {
  28102. set: function (callback) {
  28103. if (this._onBindObserver) {
  28104. this.onBindObservable.remove(this._onBindObserver);
  28105. }
  28106. this._onBindObserver = this.onBindObservable.add(callback);
  28107. },
  28108. enumerable: true,
  28109. configurable: true
  28110. });
  28111. Object.defineProperty(Material.prototype, "alphaMode", {
  28112. get: function () {
  28113. return this._alphaMode;
  28114. },
  28115. set: function (value) {
  28116. if (this._alphaMode === value) {
  28117. return;
  28118. }
  28119. this._alphaMode = value;
  28120. this.markAsDirty(Material.TextureDirtyFlag);
  28121. },
  28122. enumerable: true,
  28123. configurable: true
  28124. });
  28125. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28126. get: function () {
  28127. return this._needDepthPrePass;
  28128. },
  28129. set: function (value) {
  28130. if (this._needDepthPrePass === value) {
  28131. return;
  28132. }
  28133. this._needDepthPrePass = value;
  28134. if (this._needDepthPrePass) {
  28135. this.checkReadyOnEveryCall = true;
  28136. }
  28137. },
  28138. enumerable: true,
  28139. configurable: true
  28140. });
  28141. Object.defineProperty(Material.prototype, "fogEnabled", {
  28142. get: function () {
  28143. return this._fogEnabled;
  28144. },
  28145. set: function (value) {
  28146. if (this._fogEnabled === value) {
  28147. return;
  28148. }
  28149. this._fogEnabled = value;
  28150. this.markAsDirty(Material.MiscDirtyFlag);
  28151. },
  28152. enumerable: true,
  28153. configurable: true
  28154. });
  28155. Object.defineProperty(Material.prototype, "wireframe", {
  28156. get: function () {
  28157. return this._fillMode === Material.WireFrameFillMode;
  28158. },
  28159. set: function (value) {
  28160. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28161. },
  28162. enumerable: true,
  28163. configurable: true
  28164. });
  28165. Object.defineProperty(Material.prototype, "pointsCloud", {
  28166. get: function () {
  28167. return this._fillMode === Material.PointFillMode;
  28168. },
  28169. set: function (value) {
  28170. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28171. },
  28172. enumerable: true,
  28173. configurable: true
  28174. });
  28175. Object.defineProperty(Material.prototype, "fillMode", {
  28176. get: function () {
  28177. return this._fillMode;
  28178. },
  28179. set: function (value) {
  28180. if (this._fillMode === value) {
  28181. return;
  28182. }
  28183. this._fillMode = value;
  28184. this.markAsDirty(Material.MiscDirtyFlag);
  28185. },
  28186. enumerable: true,
  28187. configurable: true
  28188. });
  28189. /**
  28190. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28191. * subclasses should override adding information pertainent to themselves
  28192. */
  28193. Material.prototype.toString = function (fullDetails) {
  28194. var ret = "Name: " + this.name;
  28195. if (fullDetails) {
  28196. }
  28197. return ret;
  28198. };
  28199. /**
  28200. * Child classes can use it to update shaders
  28201. */
  28202. Material.prototype.getClassName = function () {
  28203. return "Material";
  28204. };
  28205. Object.defineProperty(Material.prototype, "isFrozen", {
  28206. get: function () {
  28207. return this.checkReadyOnlyOnce;
  28208. },
  28209. enumerable: true,
  28210. configurable: true
  28211. });
  28212. Material.prototype.freeze = function () {
  28213. this.checkReadyOnlyOnce = true;
  28214. };
  28215. Material.prototype.unfreeze = function () {
  28216. this.checkReadyOnlyOnce = false;
  28217. };
  28218. Material.prototype.isReady = function (mesh, useInstances) {
  28219. return true;
  28220. };
  28221. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28222. return false;
  28223. };
  28224. Material.prototype.getEffect = function () {
  28225. return this._effect;
  28226. };
  28227. Material.prototype.getScene = function () {
  28228. return this._scene;
  28229. };
  28230. Material.prototype.needAlphaBlending = function () {
  28231. return (this.alpha < 1.0);
  28232. };
  28233. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28234. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28235. };
  28236. Material.prototype.needAlphaTesting = function () {
  28237. return false;
  28238. };
  28239. Material.prototype.getAlphaTestTexture = function () {
  28240. return null;
  28241. };
  28242. Material.prototype.markDirty = function () {
  28243. this._wasPreviouslyReady = false;
  28244. };
  28245. Material.prototype._preBind = function (effect, overrideOrientation) {
  28246. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28247. var engine = this._scene.getEngine();
  28248. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28249. var reverse = orientation === Material.ClockWiseSideOrientation;
  28250. engine.enableEffect(effect ? effect : this._effect);
  28251. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28252. return reverse;
  28253. };
  28254. Material.prototype.bind = function (world, mesh) {
  28255. };
  28256. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28257. };
  28258. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28259. };
  28260. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28261. sceneUbo.bindToEffect(effect, "Scene");
  28262. };
  28263. Material.prototype.bindView = function (effect) {
  28264. if (!this._useUBO) {
  28265. effect.setMatrix("view", this.getScene().getViewMatrix());
  28266. }
  28267. else {
  28268. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28269. }
  28270. };
  28271. Material.prototype.bindViewProjection = function (effect) {
  28272. if (!this._useUBO) {
  28273. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28274. }
  28275. else {
  28276. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28277. }
  28278. };
  28279. Material.prototype._afterBind = function (mesh) {
  28280. this._scene._cachedMaterial = this;
  28281. if (mesh) {
  28282. this._scene._cachedVisibility = mesh.visibility;
  28283. }
  28284. else {
  28285. this._scene._cachedVisibility = 1;
  28286. }
  28287. if (mesh) {
  28288. this.onBindObservable.notifyObservers(mesh);
  28289. }
  28290. if (this.disableDepthWrite) {
  28291. var engine = this._scene.getEngine();
  28292. this._cachedDepthWriteState = engine.getDepthWrite();
  28293. engine.setDepthWrite(false);
  28294. }
  28295. };
  28296. Material.prototype.unbind = function () {
  28297. this.onUnBindObservable.notifyObservers(this);
  28298. if (this.disableDepthWrite) {
  28299. var engine = this._scene.getEngine();
  28300. engine.setDepthWrite(this._cachedDepthWriteState);
  28301. }
  28302. };
  28303. Material.prototype.getActiveTextures = function () {
  28304. return [];
  28305. };
  28306. Material.prototype.hasTexture = function (texture) {
  28307. return false;
  28308. };
  28309. Material.prototype.clone = function (name) {
  28310. return null;
  28311. };
  28312. Material.prototype.getBindedMeshes = function () {
  28313. var result = new Array();
  28314. for (var index = 0; index < this._scene.meshes.length; index++) {
  28315. var mesh = this._scene.meshes[index];
  28316. if (mesh.material === this) {
  28317. result.push(mesh);
  28318. }
  28319. }
  28320. return result;
  28321. };
  28322. /**
  28323. * Force shader compilation including textures ready check
  28324. */
  28325. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28326. var _this = this;
  28327. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28328. var subMesh = new BABYLON.BaseSubMesh();
  28329. var scene = this.getScene();
  28330. var engine = scene.getEngine();
  28331. var checkReady = function () {
  28332. if (!_this._scene || !_this._scene.getEngine()) {
  28333. return;
  28334. }
  28335. if (subMesh._materialDefines) {
  28336. subMesh._materialDefines._renderId = -1;
  28337. }
  28338. var alphaTestState = engine.getAlphaTesting();
  28339. var clipPlaneState = scene.clipPlane;
  28340. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28341. if (localOptions.clipPlane) {
  28342. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28343. }
  28344. if (_this.storeEffectOnSubMeshes) {
  28345. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28346. if (onCompiled) {
  28347. onCompiled(_this);
  28348. }
  28349. }
  28350. else {
  28351. setTimeout(checkReady, 16);
  28352. }
  28353. }
  28354. else {
  28355. if (_this.isReady(mesh)) {
  28356. if (onCompiled) {
  28357. onCompiled(_this);
  28358. }
  28359. }
  28360. else {
  28361. setTimeout(checkReady, 16);
  28362. }
  28363. }
  28364. engine.setAlphaTesting(alphaTestState);
  28365. if (options && options.clipPlane) {
  28366. scene.clipPlane = clipPlaneState;
  28367. }
  28368. };
  28369. checkReady();
  28370. };
  28371. Material.prototype.markAsDirty = function (flag) {
  28372. if (flag & Material.TextureDirtyFlag) {
  28373. this._markAllSubMeshesAsTexturesDirty();
  28374. }
  28375. if (flag & Material.LightDirtyFlag) {
  28376. this._markAllSubMeshesAsLightsDirty();
  28377. }
  28378. if (flag & Material.FresnelDirtyFlag) {
  28379. this._markAllSubMeshesAsFresnelDirty();
  28380. }
  28381. if (flag & Material.AttributesDirtyFlag) {
  28382. this._markAllSubMeshesAsAttributesDirty();
  28383. }
  28384. if (flag & Material.MiscDirtyFlag) {
  28385. this._markAllSubMeshesAsMiscDirty();
  28386. }
  28387. this.getScene().resetCachedMaterial();
  28388. };
  28389. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28390. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28391. var mesh = _a[_i];
  28392. if (!mesh.subMeshes) {
  28393. continue;
  28394. }
  28395. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28396. var subMesh = _c[_b];
  28397. if (subMesh.getMaterial() !== this) {
  28398. continue;
  28399. }
  28400. if (!subMesh._materialDefines) {
  28401. continue;
  28402. }
  28403. func(subMesh._materialDefines);
  28404. }
  28405. }
  28406. };
  28407. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28408. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28409. };
  28410. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28411. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28412. };
  28413. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28414. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28415. };
  28416. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28417. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28418. };
  28419. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28420. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28421. };
  28422. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28423. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28424. };
  28425. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28426. // Animations
  28427. this.getScene().stopAnimation(this);
  28428. // Remove from scene
  28429. var index = this._scene.materials.indexOf(this);
  28430. if (index >= 0) {
  28431. this._scene.materials.splice(index, 1);
  28432. }
  28433. // Remove from meshes
  28434. for (index = 0; index < this._scene.meshes.length; index++) {
  28435. var mesh = this._scene.meshes[index];
  28436. if (mesh.material === this) {
  28437. mesh.material = null;
  28438. if (mesh.geometry) {
  28439. var geometry = (mesh.geometry);
  28440. if (this.storeEffectOnSubMeshes) {
  28441. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28442. var subMesh = _a[_i];
  28443. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28444. if (forceDisposeEffect && subMesh._materialEffect) {
  28445. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28446. }
  28447. }
  28448. }
  28449. else {
  28450. geometry._releaseVertexArrayObject(this._effect);
  28451. }
  28452. }
  28453. }
  28454. }
  28455. this._uniformBuffer.dispose();
  28456. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28457. if (forceDisposeEffect && this._effect) {
  28458. if (!this.storeEffectOnSubMeshes) {
  28459. this._scene.getEngine()._releaseEffect(this._effect);
  28460. }
  28461. this._effect = null;
  28462. }
  28463. // Callback
  28464. this.onDisposeObservable.notifyObservers(this);
  28465. this.onDisposeObservable.clear();
  28466. this.onBindObservable.clear();
  28467. this.onUnBindObservable.clear();
  28468. };
  28469. Material.prototype.serialize = function () {
  28470. return BABYLON.SerializationHelper.Serialize(this);
  28471. };
  28472. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28473. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28474. multiMaterial.id = parsedMultiMaterial.id;
  28475. if (BABYLON.Tags) {
  28476. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28477. }
  28478. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28479. var subMatId = parsedMultiMaterial.materials[matIndex];
  28480. if (subMatId) {
  28481. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28482. }
  28483. else {
  28484. multiMaterial.subMaterials.push(null);
  28485. }
  28486. }
  28487. return multiMaterial;
  28488. };
  28489. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28490. if (!parsedMaterial.customType) {
  28491. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28492. }
  28493. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28494. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28495. if (!BABYLON.LegacyPBRMaterial) {
  28496. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28497. return;
  28498. }
  28499. }
  28500. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28501. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28502. ;
  28503. };
  28504. // Triangle views
  28505. Material._TriangleFillMode = 0;
  28506. Material._WireFrameFillMode = 1;
  28507. Material._PointFillMode = 2;
  28508. // Draw modes
  28509. Material._PointListDrawMode = 3;
  28510. Material._LineListDrawMode = 4;
  28511. Material._LineLoopDrawMode = 5;
  28512. Material._LineStripDrawMode = 6;
  28513. Material._TriangleStripDrawMode = 7;
  28514. Material._TriangleFanDrawMode = 8;
  28515. Material._ClockWiseSideOrientation = 0;
  28516. Material._CounterClockWiseSideOrientation = 1;
  28517. Material._TextureDirtyFlag = 1;
  28518. Material._LightDirtyFlag = 2;
  28519. Material._FresnelDirtyFlag = 4;
  28520. Material._AttributesDirtyFlag = 8;
  28521. Material._MiscDirtyFlag = 16;
  28522. __decorate([
  28523. BABYLON.serialize()
  28524. ], Material.prototype, "id", void 0);
  28525. __decorate([
  28526. BABYLON.serialize()
  28527. ], Material.prototype, "name", void 0);
  28528. __decorate([
  28529. BABYLON.serialize()
  28530. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28531. __decorate([
  28532. BABYLON.serialize()
  28533. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28534. __decorate([
  28535. BABYLON.serialize()
  28536. ], Material.prototype, "state", void 0);
  28537. __decorate([
  28538. BABYLON.serialize()
  28539. ], Material.prototype, "alpha", void 0);
  28540. __decorate([
  28541. BABYLON.serialize("backFaceCulling")
  28542. ], Material.prototype, "_backFaceCulling", void 0);
  28543. __decorate([
  28544. BABYLON.serialize()
  28545. ], Material.prototype, "sideOrientation", void 0);
  28546. __decorate([
  28547. BABYLON.serialize("alphaMode")
  28548. ], Material.prototype, "_alphaMode", void 0);
  28549. __decorate([
  28550. BABYLON.serialize()
  28551. ], Material.prototype, "_needDepthPrePass", void 0);
  28552. __decorate([
  28553. BABYLON.serialize()
  28554. ], Material.prototype, "disableDepthWrite", void 0);
  28555. __decorate([
  28556. BABYLON.serialize()
  28557. ], Material.prototype, "forceDepthWrite", void 0);
  28558. __decorate([
  28559. BABYLON.serialize()
  28560. ], Material.prototype, "separateCullingPass", void 0);
  28561. __decorate([
  28562. BABYLON.serialize("fogEnabled")
  28563. ], Material.prototype, "_fogEnabled", void 0);
  28564. __decorate([
  28565. BABYLON.serialize()
  28566. ], Material.prototype, "pointSize", void 0);
  28567. __decorate([
  28568. BABYLON.serialize()
  28569. ], Material.prototype, "zOffset", void 0);
  28570. __decorate([
  28571. BABYLON.serialize()
  28572. ], Material.prototype, "wireframe", null);
  28573. __decorate([
  28574. BABYLON.serialize()
  28575. ], Material.prototype, "pointsCloud", null);
  28576. __decorate([
  28577. BABYLON.serialize()
  28578. ], Material.prototype, "fillMode", null);
  28579. return Material;
  28580. }());
  28581. BABYLON.Material = Material;
  28582. })(BABYLON || (BABYLON = {}));
  28583. //# sourceMappingURL=babylon.material.js.map
  28584. var BABYLON;
  28585. (function (BABYLON) {
  28586. var UniformBuffer = /** @class */ (function () {
  28587. /**
  28588. * Uniform buffer objects.
  28589. *
  28590. * Handles blocks of uniform on the GPU.
  28591. *
  28592. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28593. *
  28594. * For more information, please refer to :
  28595. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28596. */
  28597. function UniformBuffer(engine, data, dynamic) {
  28598. this._engine = engine;
  28599. this._noUBO = !engine.supportsUniformBuffers;
  28600. this._dynamic = dynamic;
  28601. this._data = data || [];
  28602. this._uniformLocations = {};
  28603. this._uniformSizes = {};
  28604. this._uniformLocationPointer = 0;
  28605. this._needSync = false;
  28606. if (this._noUBO) {
  28607. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28608. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28609. this.updateFloat = this._updateFloatForEffect;
  28610. this.updateFloat2 = this._updateFloat2ForEffect;
  28611. this.updateFloat3 = this._updateFloat3ForEffect;
  28612. this.updateFloat4 = this._updateFloat4ForEffect;
  28613. this.updateMatrix = this._updateMatrixForEffect;
  28614. this.updateVector3 = this._updateVector3ForEffect;
  28615. this.updateVector4 = this._updateVector4ForEffect;
  28616. this.updateColor3 = this._updateColor3ForEffect;
  28617. this.updateColor4 = this._updateColor4ForEffect;
  28618. }
  28619. else {
  28620. this._engine._uniformBuffers.push(this);
  28621. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28622. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28623. this.updateFloat = this._updateFloatForUniform;
  28624. this.updateFloat2 = this._updateFloat2ForUniform;
  28625. this.updateFloat3 = this._updateFloat3ForUniform;
  28626. this.updateFloat4 = this._updateFloat4ForUniform;
  28627. this.updateMatrix = this._updateMatrixForUniform;
  28628. this.updateVector3 = this._updateVector3ForUniform;
  28629. this.updateVector4 = this._updateVector4ForUniform;
  28630. this.updateColor3 = this._updateColor3ForUniform;
  28631. this.updateColor4 = this._updateColor4ForUniform;
  28632. }
  28633. }
  28634. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28635. // Properties
  28636. /**
  28637. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28638. * or just falling back on setUniformXXX calls.
  28639. */
  28640. get: function () {
  28641. return !this._noUBO;
  28642. },
  28643. enumerable: true,
  28644. configurable: true
  28645. });
  28646. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28647. /**
  28648. * Indicates if the WebGL underlying uniform buffer is in sync
  28649. * with the javascript cache data.
  28650. */
  28651. get: function () {
  28652. return !this._needSync;
  28653. },
  28654. enumerable: true,
  28655. configurable: true
  28656. });
  28657. /**
  28658. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28659. * Also, a dynamic UniformBuffer will disable cache verification and always
  28660. * update the underlying WebGL uniform buffer to the GPU.
  28661. */
  28662. UniformBuffer.prototype.isDynamic = function () {
  28663. return this._dynamic !== undefined;
  28664. };
  28665. /**
  28666. * The data cache on JS side.
  28667. */
  28668. UniformBuffer.prototype.getData = function () {
  28669. return this._bufferData;
  28670. };
  28671. /**
  28672. * The underlying WebGL Uniform buffer.
  28673. */
  28674. UniformBuffer.prototype.getBuffer = function () {
  28675. return this._buffer;
  28676. };
  28677. /**
  28678. * std140 layout specifies how to align data within an UBO structure.
  28679. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28680. * for specs.
  28681. */
  28682. UniformBuffer.prototype._fillAlignment = function (size) {
  28683. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28684. // and 4x4 matrices
  28685. // TODO : change if other types are used
  28686. var alignment;
  28687. if (size <= 2) {
  28688. alignment = size;
  28689. }
  28690. else {
  28691. alignment = 4;
  28692. }
  28693. if ((this._uniformLocationPointer % alignment) !== 0) {
  28694. var oldPointer = this._uniformLocationPointer;
  28695. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28696. var diff = this._uniformLocationPointer - oldPointer;
  28697. for (var i = 0; i < diff; i++) {
  28698. this._data.push(0);
  28699. }
  28700. }
  28701. };
  28702. /**
  28703. * Adds an uniform in the buffer.
  28704. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28705. * for the layout to be correct !
  28706. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28707. * @param {number|number[]} size Data size, or data directly.
  28708. */
  28709. UniformBuffer.prototype.addUniform = function (name, size) {
  28710. if (this._noUBO) {
  28711. return;
  28712. }
  28713. if (this._uniformLocations[name] !== undefined) {
  28714. // Already existing uniform
  28715. return;
  28716. }
  28717. // This function must be called in the order of the shader layout !
  28718. // size can be the size of the uniform, or data directly
  28719. var data;
  28720. if (size instanceof Array) {
  28721. data = size;
  28722. size = data.length;
  28723. }
  28724. else {
  28725. size = size;
  28726. data = [];
  28727. // Fill with zeros
  28728. for (var i = 0; i < size; i++) {
  28729. data.push(0);
  28730. }
  28731. }
  28732. this._fillAlignment(size);
  28733. this._uniformSizes[name] = size;
  28734. this._uniformLocations[name] = this._uniformLocationPointer;
  28735. this._uniformLocationPointer += size;
  28736. for (var i = 0; i < size; i++) {
  28737. this._data.push(data[i]);
  28738. }
  28739. this._needSync = true;
  28740. };
  28741. /**
  28742. * Wrapper for addUniform.
  28743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28744. * @param {Matrix} mat A 4x4 matrix.
  28745. */
  28746. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28747. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28748. };
  28749. /**
  28750. * Wrapper for addUniform.
  28751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28752. * @param {number} x
  28753. * @param {number} y
  28754. */
  28755. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28756. var temp = [x, y];
  28757. this.addUniform(name, temp);
  28758. };
  28759. /**
  28760. * Wrapper for addUniform.
  28761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28762. * @param {number} x
  28763. * @param {number} y
  28764. * @param {number} z
  28765. */
  28766. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28767. var temp = [x, y, z];
  28768. this.addUniform(name, temp);
  28769. };
  28770. /**
  28771. * Wrapper for addUniform.
  28772. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28773. * @param {Color3} color
  28774. */
  28775. UniformBuffer.prototype.addColor3 = function (name, color) {
  28776. var temp = new Array();
  28777. color.toArray(temp);
  28778. this.addUniform(name, temp);
  28779. };
  28780. /**
  28781. * Wrapper for addUniform.
  28782. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28783. * @param {Color3} color
  28784. * @param {number} alpha
  28785. */
  28786. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28787. var temp = new Array();
  28788. color.toArray(temp);
  28789. temp.push(alpha);
  28790. this.addUniform(name, temp);
  28791. };
  28792. /**
  28793. * Wrapper for addUniform.
  28794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28795. * @param {Vector3} vector
  28796. */
  28797. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28798. var temp = new Array();
  28799. vector.toArray(temp);
  28800. this.addUniform(name, temp);
  28801. };
  28802. /**
  28803. * Wrapper for addUniform.
  28804. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28805. */
  28806. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28807. this.addUniform(name, 12);
  28808. };
  28809. /**
  28810. * Wrapper for addUniform.
  28811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28812. */
  28813. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28814. this.addUniform(name, 8);
  28815. };
  28816. /**
  28817. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28818. */
  28819. UniformBuffer.prototype.create = function () {
  28820. if (this._noUBO) {
  28821. return;
  28822. }
  28823. if (this._buffer) {
  28824. return; // nothing to do
  28825. }
  28826. // See spec, alignment must be filled as a vec4
  28827. this._fillAlignment(4);
  28828. this._bufferData = new Float32Array(this._data);
  28829. this._rebuild();
  28830. this._needSync = true;
  28831. };
  28832. UniformBuffer.prototype._rebuild = function () {
  28833. if (this._noUBO) {
  28834. return;
  28835. }
  28836. if (this._dynamic) {
  28837. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28838. }
  28839. else {
  28840. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28841. }
  28842. };
  28843. /**
  28844. * Updates the WebGL Uniform Buffer on the GPU.
  28845. * If the `dynamic` flag is set to true, no cache comparison is done.
  28846. * Otherwise, the buffer will be updated only if the cache differs.
  28847. */
  28848. UniformBuffer.prototype.update = function () {
  28849. if (!this._buffer) {
  28850. this.create();
  28851. return;
  28852. }
  28853. if (!this._dynamic && !this._needSync) {
  28854. return;
  28855. }
  28856. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28857. this._needSync = false;
  28858. };
  28859. /**
  28860. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28861. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28862. * @param {number[]|Float32Array} data Flattened data
  28863. * @param {number} size Size of the data.
  28864. */
  28865. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28866. var location = this._uniformLocations[uniformName];
  28867. if (location === undefined) {
  28868. if (this._buffer) {
  28869. // Cannot add an uniform if the buffer is already created
  28870. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28871. return;
  28872. }
  28873. this.addUniform(uniformName, size);
  28874. location = this._uniformLocations[uniformName];
  28875. }
  28876. if (!this._buffer) {
  28877. this.create();
  28878. }
  28879. if (!this._dynamic) {
  28880. // Cache for static uniform buffers
  28881. var changed = false;
  28882. for (var i = 0; i < size; i++) {
  28883. if (this._bufferData[location + i] !== data[i]) {
  28884. changed = true;
  28885. this._bufferData[location + i] = data[i];
  28886. }
  28887. }
  28888. this._needSync = this._needSync || changed;
  28889. }
  28890. else {
  28891. // No cache for dynamic
  28892. for (var i = 0; i < size; i++) {
  28893. this._bufferData[location + i] = data[i];
  28894. }
  28895. }
  28896. };
  28897. // Update methods
  28898. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28899. // To match std140, matrix must be realigned
  28900. for (var i = 0; i < 3; i++) {
  28901. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28902. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28903. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28904. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28905. }
  28906. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28907. };
  28908. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28909. this._currentEffect.setMatrix3x3(name, matrix);
  28910. };
  28911. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28912. this._currentEffect.setMatrix2x2(name, matrix);
  28913. };
  28914. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28915. // To match std140, matrix must be realigned
  28916. for (var i = 0; i < 2; i++) {
  28917. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28918. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28919. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28920. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28921. }
  28922. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28923. };
  28924. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28925. this._currentEffect.setFloat(name, x);
  28926. };
  28927. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28928. UniformBuffer._tempBuffer[0] = x;
  28929. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28930. };
  28931. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28932. if (suffix === void 0) { suffix = ""; }
  28933. this._currentEffect.setFloat2(name + suffix, x, y);
  28934. };
  28935. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28936. if (suffix === void 0) { suffix = ""; }
  28937. UniformBuffer._tempBuffer[0] = x;
  28938. UniformBuffer._tempBuffer[1] = y;
  28939. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28940. };
  28941. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28942. if (suffix === void 0) { suffix = ""; }
  28943. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28944. };
  28945. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28946. if (suffix === void 0) { suffix = ""; }
  28947. UniformBuffer._tempBuffer[0] = x;
  28948. UniformBuffer._tempBuffer[1] = y;
  28949. UniformBuffer._tempBuffer[2] = z;
  28950. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28951. };
  28952. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28953. if (suffix === void 0) { suffix = ""; }
  28954. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28955. };
  28956. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28957. if (suffix === void 0) { suffix = ""; }
  28958. UniformBuffer._tempBuffer[0] = x;
  28959. UniformBuffer._tempBuffer[1] = y;
  28960. UniformBuffer._tempBuffer[2] = z;
  28961. UniformBuffer._tempBuffer[3] = w;
  28962. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28963. };
  28964. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28965. this._currentEffect.setMatrix(name, mat);
  28966. };
  28967. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28968. this.updateUniform(name, mat.toArray(), 16);
  28969. };
  28970. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28971. this._currentEffect.setVector3(name, vector);
  28972. };
  28973. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28974. vector.toArray(UniformBuffer._tempBuffer);
  28975. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28976. };
  28977. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28978. this._currentEffect.setVector4(name, vector);
  28979. };
  28980. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28981. vector.toArray(UniformBuffer._tempBuffer);
  28982. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28983. };
  28984. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28985. if (suffix === void 0) { suffix = ""; }
  28986. this._currentEffect.setColor3(name + suffix, color);
  28987. };
  28988. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28989. if (suffix === void 0) { suffix = ""; }
  28990. color.toArray(UniformBuffer._tempBuffer);
  28991. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28992. };
  28993. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28994. if (suffix === void 0) { suffix = ""; }
  28995. this._currentEffect.setColor4(name + suffix, color, alpha);
  28996. };
  28997. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28998. if (suffix === void 0) { suffix = ""; }
  28999. color.toArray(UniformBuffer._tempBuffer);
  29000. UniformBuffer._tempBuffer[3] = alpha;
  29001. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29002. };
  29003. /**
  29004. * Sets a sampler uniform on the effect.
  29005. * @param {string} name Name of the sampler.
  29006. * @param {Texture} texture
  29007. */
  29008. UniformBuffer.prototype.setTexture = function (name, texture) {
  29009. this._currentEffect.setTexture(name, texture);
  29010. };
  29011. /**
  29012. * Directly updates the value of the uniform in the cache AND on the GPU.
  29013. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29014. * @param {number[]|Float32Array} data Flattened data
  29015. */
  29016. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29017. this.updateUniform(uniformName, data, data.length);
  29018. this.update();
  29019. };
  29020. /**
  29021. * Binds this uniform buffer to an effect.
  29022. * @param {Effect} effect
  29023. * @param {string} name Name of the uniform block in the shader.
  29024. */
  29025. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29026. this._currentEffect = effect;
  29027. if (this._noUBO || !this._buffer) {
  29028. return;
  29029. }
  29030. effect.bindUniformBuffer(this._buffer, name);
  29031. };
  29032. /**
  29033. * Disposes the uniform buffer.
  29034. */
  29035. UniformBuffer.prototype.dispose = function () {
  29036. if (this._noUBO) {
  29037. return;
  29038. }
  29039. var index = this._engine._uniformBuffers.indexOf(this);
  29040. if (index !== -1) {
  29041. this._engine._uniformBuffers.splice(index, 1);
  29042. }
  29043. if (!this._buffer) {
  29044. return;
  29045. }
  29046. if (this._engine._releaseBuffer(this._buffer)) {
  29047. this._buffer = null;
  29048. }
  29049. };
  29050. // Pool for avoiding memory leaks
  29051. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29052. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29053. return UniformBuffer;
  29054. }());
  29055. BABYLON.UniformBuffer = UniformBuffer;
  29056. })(BABYLON || (BABYLON = {}));
  29057. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29058. var BABYLON;
  29059. (function (BABYLON) {
  29060. var VertexData = /** @class */ (function () {
  29061. function VertexData() {
  29062. }
  29063. VertexData.prototype.set = function (data, kind) {
  29064. switch (kind) {
  29065. case BABYLON.VertexBuffer.PositionKind:
  29066. this.positions = data;
  29067. break;
  29068. case BABYLON.VertexBuffer.NormalKind:
  29069. this.normals = data;
  29070. break;
  29071. case BABYLON.VertexBuffer.TangentKind:
  29072. this.tangents = data;
  29073. break;
  29074. case BABYLON.VertexBuffer.UVKind:
  29075. this.uvs = data;
  29076. break;
  29077. case BABYLON.VertexBuffer.UV2Kind:
  29078. this.uvs2 = data;
  29079. break;
  29080. case BABYLON.VertexBuffer.UV3Kind:
  29081. this.uvs3 = data;
  29082. break;
  29083. case BABYLON.VertexBuffer.UV4Kind:
  29084. this.uvs4 = data;
  29085. break;
  29086. case BABYLON.VertexBuffer.UV5Kind:
  29087. this.uvs5 = data;
  29088. break;
  29089. case BABYLON.VertexBuffer.UV6Kind:
  29090. this.uvs6 = data;
  29091. break;
  29092. case BABYLON.VertexBuffer.ColorKind:
  29093. this.colors = data;
  29094. break;
  29095. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29096. this.matricesIndices = data;
  29097. break;
  29098. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29099. this.matricesWeights = data;
  29100. break;
  29101. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29102. this.matricesIndicesExtra = data;
  29103. break;
  29104. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29105. this.matricesWeightsExtra = data;
  29106. break;
  29107. }
  29108. };
  29109. /**
  29110. * Associates the vertexData to the passed Mesh.
  29111. * Sets it as updatable or not (default `false`).
  29112. * Returns the VertexData.
  29113. */
  29114. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29115. this._applyTo(mesh, updatable);
  29116. return this;
  29117. };
  29118. /**
  29119. * Associates the vertexData to the passed Geometry.
  29120. * Sets it as updatable or not (default `false`).
  29121. * Returns the VertexData.
  29122. */
  29123. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29124. this._applyTo(geometry, updatable);
  29125. return this;
  29126. };
  29127. /**
  29128. * Updates the associated mesh.
  29129. * Returns the VertexData.
  29130. */
  29131. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29132. this._update(mesh);
  29133. return this;
  29134. };
  29135. /**
  29136. * Updates the associated geometry.
  29137. * Returns the VertexData.
  29138. */
  29139. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29140. this._update(geometry);
  29141. return this;
  29142. };
  29143. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29144. if (updatable === void 0) { updatable = false; }
  29145. if (this.positions) {
  29146. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29147. }
  29148. if (this.normals) {
  29149. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29150. }
  29151. if (this.tangents) {
  29152. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29153. }
  29154. if (this.uvs) {
  29155. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29156. }
  29157. if (this.uvs2) {
  29158. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29159. }
  29160. if (this.uvs3) {
  29161. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29162. }
  29163. if (this.uvs4) {
  29164. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29165. }
  29166. if (this.uvs5) {
  29167. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29168. }
  29169. if (this.uvs6) {
  29170. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29171. }
  29172. if (this.colors) {
  29173. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29174. }
  29175. if (this.matricesIndices) {
  29176. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29177. }
  29178. if (this.matricesWeights) {
  29179. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29180. }
  29181. if (this.matricesIndicesExtra) {
  29182. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29183. }
  29184. if (this.matricesWeightsExtra) {
  29185. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29186. }
  29187. if (this.indices) {
  29188. meshOrGeometry.setIndices(this.indices, null, updatable);
  29189. }
  29190. return this;
  29191. };
  29192. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29193. if (this.positions) {
  29194. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29195. }
  29196. if (this.normals) {
  29197. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29198. }
  29199. if (this.tangents) {
  29200. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29201. }
  29202. if (this.uvs) {
  29203. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29204. }
  29205. if (this.uvs2) {
  29206. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29207. }
  29208. if (this.uvs3) {
  29209. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29210. }
  29211. if (this.uvs4) {
  29212. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29213. }
  29214. if (this.uvs5) {
  29215. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29216. }
  29217. if (this.uvs6) {
  29218. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29219. }
  29220. if (this.colors) {
  29221. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29222. }
  29223. if (this.matricesIndices) {
  29224. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29225. }
  29226. if (this.matricesWeights) {
  29227. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29228. }
  29229. if (this.matricesIndicesExtra) {
  29230. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29231. }
  29232. if (this.matricesWeightsExtra) {
  29233. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29234. }
  29235. if (this.indices) {
  29236. meshOrGeometry.setIndices(this.indices, null);
  29237. }
  29238. return this;
  29239. };
  29240. /**
  29241. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29242. * Returns the VertexData.
  29243. */
  29244. VertexData.prototype.transform = function (matrix) {
  29245. var transformed = BABYLON.Vector3.Zero();
  29246. var index;
  29247. if (this.positions) {
  29248. var position = BABYLON.Vector3.Zero();
  29249. for (index = 0; index < this.positions.length; index += 3) {
  29250. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29251. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29252. this.positions[index] = transformed.x;
  29253. this.positions[index + 1] = transformed.y;
  29254. this.positions[index + 2] = transformed.z;
  29255. }
  29256. }
  29257. if (this.normals) {
  29258. var normal = BABYLON.Vector3.Zero();
  29259. for (index = 0; index < this.normals.length; index += 3) {
  29260. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29261. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29262. this.normals[index] = transformed.x;
  29263. this.normals[index + 1] = transformed.y;
  29264. this.normals[index + 2] = transformed.z;
  29265. }
  29266. }
  29267. if (this.tangents) {
  29268. var tangent = BABYLON.Vector4.Zero();
  29269. var tangentTransformed = BABYLON.Vector4.Zero();
  29270. for (index = 0; index < this.tangents.length; index += 4) {
  29271. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29272. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29273. this.tangents[index] = tangentTransformed.x;
  29274. this.tangents[index + 1] = tangentTransformed.y;
  29275. this.tangents[index + 2] = tangentTransformed.z;
  29276. this.tangents[index + 3] = tangentTransformed.w;
  29277. }
  29278. }
  29279. return this;
  29280. };
  29281. /**
  29282. * Merges the passed VertexData into the current one.
  29283. * Returns the modified VertexData.
  29284. */
  29285. VertexData.prototype.merge = function (other, options) {
  29286. options = options || {};
  29287. if (other.indices) {
  29288. if (!this.indices) {
  29289. this.indices = [];
  29290. }
  29291. var offset = this.positions ? this.positions.length / 3 : 0;
  29292. for (var index = 0; index < other.indices.length; index++) {
  29293. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29294. this.indices.push(other.indices[index] + offset);
  29295. }
  29296. }
  29297. this.positions = this._mergeElement(this.positions, other.positions);
  29298. if (!this.positions) {
  29299. return this;
  29300. }
  29301. var count = this.positions.length / 3;
  29302. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29303. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29304. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29305. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29306. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29307. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29308. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29309. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29310. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29311. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29312. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29313. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29314. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29315. return this;
  29316. };
  29317. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29318. if (length === void 0) { length = 0; }
  29319. if (defaultValue === void 0) { defaultValue = 0; }
  29320. if (!other && !source) {
  29321. return null;
  29322. }
  29323. if (!other) {
  29324. var padding = new Float32Array(source.length);
  29325. padding.fill(defaultValue);
  29326. return this._mergeElement(source, padding, length);
  29327. }
  29328. if (!source) {
  29329. if (length === 0 || length === other.length) {
  29330. return other;
  29331. }
  29332. var padding = new Float32Array(length - other.length);
  29333. padding.fill(defaultValue);
  29334. return this._mergeElement(padding, other, length);
  29335. }
  29336. var len = other.length + source.length;
  29337. var isSrcTypedArray = source instanceof Float32Array;
  29338. var isOthTypedArray = other instanceof Float32Array;
  29339. // use non-loop method when the source is Float32Array
  29340. if (isSrcTypedArray) {
  29341. var ret32 = new Float32Array(len);
  29342. ret32.set(source);
  29343. ret32.set(other, source.length);
  29344. return ret32;
  29345. // source is number[], when other is also use concat
  29346. }
  29347. else if (!isOthTypedArray) {
  29348. return source.concat(other);
  29349. // source is a number[], but other is a Float32Array, loop required
  29350. }
  29351. else {
  29352. var ret = source.slice(0); // copy source to a separate array
  29353. for (var i = 0, len = other.length; i < len; i++) {
  29354. ret.push(other[i]);
  29355. }
  29356. return ret;
  29357. }
  29358. };
  29359. /**
  29360. * Serializes the VertexData.
  29361. * Returns a serialized object.
  29362. */
  29363. VertexData.prototype.serialize = function () {
  29364. var serializationObject = this.serialize();
  29365. if (this.positions) {
  29366. serializationObject.positions = this.positions;
  29367. }
  29368. if (this.normals) {
  29369. serializationObject.normals = this.normals;
  29370. }
  29371. if (this.tangents) {
  29372. serializationObject.tangents = this.tangents;
  29373. }
  29374. if (this.uvs) {
  29375. serializationObject.uvs = this.uvs;
  29376. }
  29377. if (this.uvs2) {
  29378. serializationObject.uvs2 = this.uvs2;
  29379. }
  29380. if (this.uvs3) {
  29381. serializationObject.uvs3 = this.uvs3;
  29382. }
  29383. if (this.uvs4) {
  29384. serializationObject.uvs4 = this.uvs4;
  29385. }
  29386. if (this.uvs5) {
  29387. serializationObject.uvs5 = this.uvs5;
  29388. }
  29389. if (this.uvs6) {
  29390. serializationObject.uvs6 = this.uvs6;
  29391. }
  29392. if (this.colors) {
  29393. serializationObject.colors = this.colors;
  29394. }
  29395. if (this.matricesIndices) {
  29396. serializationObject.matricesIndices = this.matricesIndices;
  29397. serializationObject.matricesIndices._isExpanded = true;
  29398. }
  29399. if (this.matricesWeights) {
  29400. serializationObject.matricesWeights = this.matricesWeights;
  29401. }
  29402. if (this.matricesIndicesExtra) {
  29403. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29404. serializationObject.matricesIndicesExtra._isExpanded = true;
  29405. }
  29406. if (this.matricesWeightsExtra) {
  29407. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29408. }
  29409. serializationObject.indices = this.indices;
  29410. return serializationObject;
  29411. };
  29412. // Statics
  29413. /**
  29414. * Returns the object VertexData associated to the passed mesh.
  29415. */
  29416. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29417. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29418. };
  29419. /**
  29420. * Returns the object VertexData associated to the passed geometry.
  29421. */
  29422. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29423. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29424. };
  29425. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29426. var result = new VertexData();
  29427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29428. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29429. }
  29430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29431. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29432. }
  29433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29434. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29435. }
  29436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29437. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29438. }
  29439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29440. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29441. }
  29442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29443. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29444. }
  29445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29446. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29447. }
  29448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29449. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29450. }
  29451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29452. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29453. }
  29454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29455. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29456. }
  29457. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29458. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29459. }
  29460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29461. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29462. }
  29463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29464. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29465. }
  29466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29467. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29468. }
  29469. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29470. return result;
  29471. };
  29472. /**
  29473. * Creates the vertexData of the Ribbon.
  29474. */
  29475. VertexData.CreateRibbon = function (options) {
  29476. var pathArray = options.pathArray;
  29477. var closeArray = options.closeArray || false;
  29478. var closePath = options.closePath || false;
  29479. var invertUV = options.invertUV || false;
  29480. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29481. var offset = options.offset || defaultOffset;
  29482. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29483. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29484. var customUV = options.uvs;
  29485. var customColors = options.colors;
  29486. var positions = [];
  29487. var indices = [];
  29488. var normals = [];
  29489. var uvs = [];
  29490. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29491. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29492. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29493. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29494. var minlg; // minimal length among all paths from pathArray
  29495. var lg = []; // array of path lengths : nb of vertex per path
  29496. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29497. var p; // path iterator
  29498. var i; // point iterator
  29499. var j; // point iterator
  29500. // if single path in pathArray
  29501. if (pathArray.length < 2) {
  29502. var ar1 = [];
  29503. var ar2 = [];
  29504. for (i = 0; i < pathArray[0].length - offset; i++) {
  29505. ar1.push(pathArray[0][i]);
  29506. ar2.push(pathArray[0][i + offset]);
  29507. }
  29508. pathArray = [ar1, ar2];
  29509. }
  29510. // positions and horizontal distances (u)
  29511. var idc = 0;
  29512. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29513. var path;
  29514. var l;
  29515. minlg = pathArray[0].length;
  29516. var vectlg;
  29517. var dist;
  29518. for (p = 0; p < pathArray.length; p++) {
  29519. uTotalDistance[p] = 0;
  29520. us[p] = [0];
  29521. path = pathArray[p];
  29522. l = path.length;
  29523. minlg = (minlg < l) ? minlg : l;
  29524. j = 0;
  29525. while (j < l) {
  29526. positions.push(path[j].x, path[j].y, path[j].z);
  29527. if (j > 0) {
  29528. vectlg = path[j].subtract(path[j - 1]).length();
  29529. dist = vectlg + uTotalDistance[p];
  29530. us[p].push(dist);
  29531. uTotalDistance[p] = dist;
  29532. }
  29533. j++;
  29534. }
  29535. if (closePath) {
  29536. j--;
  29537. positions.push(path[0].x, path[0].y, path[0].z);
  29538. vectlg = path[j].subtract(path[0]).length();
  29539. dist = vectlg + uTotalDistance[p];
  29540. us[p].push(dist);
  29541. uTotalDistance[p] = dist;
  29542. }
  29543. lg[p] = l + closePathCorr;
  29544. idx[p] = idc;
  29545. idc += (l + closePathCorr);
  29546. }
  29547. // vertical distances (v)
  29548. var path1;
  29549. var path2;
  29550. var vertex1 = null;
  29551. var vertex2 = null;
  29552. for (i = 0; i < minlg + closePathCorr; i++) {
  29553. vTotalDistance[i] = 0;
  29554. vs[i] = [0];
  29555. for (p = 0; p < pathArray.length - 1; p++) {
  29556. path1 = pathArray[p];
  29557. path2 = pathArray[p + 1];
  29558. if (i === minlg) {
  29559. vertex1 = path1[0];
  29560. vertex2 = path2[0];
  29561. }
  29562. else {
  29563. vertex1 = path1[i];
  29564. vertex2 = path2[i];
  29565. }
  29566. vectlg = vertex2.subtract(vertex1).length();
  29567. dist = vectlg + vTotalDistance[i];
  29568. vs[i].push(dist);
  29569. vTotalDistance[i] = dist;
  29570. }
  29571. if (closeArray && vertex2 && vertex1) {
  29572. path1 = pathArray[p];
  29573. path2 = pathArray[0];
  29574. if (i === minlg) {
  29575. vertex2 = path2[0];
  29576. }
  29577. vectlg = vertex2.subtract(vertex1).length();
  29578. dist = vectlg + vTotalDistance[i];
  29579. vTotalDistance[i] = dist;
  29580. }
  29581. }
  29582. // uvs
  29583. var u;
  29584. var v;
  29585. if (customUV) {
  29586. for (p = 0; p < customUV.length; p++) {
  29587. uvs.push(customUV[p].x, customUV[p].y);
  29588. }
  29589. }
  29590. else {
  29591. for (p = 0; p < pathArray.length; p++) {
  29592. for (i = 0; i < minlg + closePathCorr; i++) {
  29593. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29594. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29595. if (invertUV) {
  29596. uvs.push(v, u);
  29597. }
  29598. else {
  29599. uvs.push(u, v);
  29600. }
  29601. }
  29602. }
  29603. }
  29604. // indices
  29605. p = 0; // path index
  29606. var pi = 0; // positions array index
  29607. var l1 = lg[p] - 1; // path1 length
  29608. var l2 = lg[p + 1] - 1; // path2 length
  29609. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29610. var shft = idx[1] - idx[0]; // shift
  29611. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29612. while (pi <= min && p < path1nb) {
  29613. // 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
  29614. indices.push(pi, pi + shft, pi + 1);
  29615. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29616. pi += 1;
  29617. if (pi === min) {
  29618. p++;
  29619. if (p === lg.length - 1) {
  29620. shft = idx[0] - idx[p];
  29621. l1 = lg[p] - 1;
  29622. l2 = lg[0] - 1;
  29623. }
  29624. else {
  29625. shft = idx[p + 1] - idx[p];
  29626. l1 = lg[p] - 1;
  29627. l2 = lg[p + 1] - 1;
  29628. }
  29629. pi = idx[p];
  29630. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29631. }
  29632. }
  29633. // normals
  29634. VertexData.ComputeNormals(positions, indices, normals);
  29635. if (closePath) {
  29636. var indexFirst = 0;
  29637. var indexLast = 0;
  29638. for (p = 0; p < pathArray.length; p++) {
  29639. indexFirst = idx[p] * 3;
  29640. if (p + 1 < pathArray.length) {
  29641. indexLast = (idx[p + 1] - 1) * 3;
  29642. }
  29643. else {
  29644. indexLast = normals.length - 3;
  29645. }
  29646. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29647. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29648. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29649. normals[indexLast] = normals[indexFirst];
  29650. normals[indexLast + 1] = normals[indexFirst + 1];
  29651. normals[indexLast + 2] = normals[indexFirst + 2];
  29652. }
  29653. }
  29654. // sides
  29655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29656. // Colors
  29657. var colors = null;
  29658. if (customColors) {
  29659. colors = new Float32Array(customColors.length * 4);
  29660. for (var c = 0; c < customColors.length; c++) {
  29661. colors[c * 4] = customColors[c].r;
  29662. colors[c * 4 + 1] = customColors[c].g;
  29663. colors[c * 4 + 2] = customColors[c].b;
  29664. colors[c * 4 + 3] = customColors[c].a;
  29665. }
  29666. }
  29667. // Result
  29668. var vertexData = new VertexData();
  29669. var positions32 = new Float32Array(positions);
  29670. var normals32 = new Float32Array(normals);
  29671. var uvs32 = new Float32Array(uvs);
  29672. vertexData.indices = indices;
  29673. vertexData.positions = positions32;
  29674. vertexData.normals = normals32;
  29675. vertexData.uvs = uvs32;
  29676. if (colors) {
  29677. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29678. }
  29679. if (closePath) {
  29680. vertexData._idx = idx;
  29681. }
  29682. return vertexData;
  29683. };
  29684. /**
  29685. * Creates the VertexData of the Box.
  29686. */
  29687. VertexData.CreateBox = function (options) {
  29688. var normalsSource = [
  29689. new BABYLON.Vector3(0, 0, 1),
  29690. new BABYLON.Vector3(0, 0, -1),
  29691. new BABYLON.Vector3(1, 0, 0),
  29692. new BABYLON.Vector3(-1, 0, 0),
  29693. new BABYLON.Vector3(0, 1, 0),
  29694. new BABYLON.Vector3(0, -1, 0)
  29695. ];
  29696. var indices = [];
  29697. var positions = [];
  29698. var normals = [];
  29699. var uvs = [];
  29700. var width = options.width || options.size || 1;
  29701. var height = options.height || options.size || 1;
  29702. var depth = options.depth || options.size || 1;
  29703. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29704. var faceUV = options.faceUV || new Array(6);
  29705. var faceColors = options.faceColors;
  29706. var colors = [];
  29707. // default face colors and UV if undefined
  29708. for (var f = 0; f < 6; f++) {
  29709. if (faceUV[f] === undefined) {
  29710. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29711. }
  29712. if (faceColors && faceColors[f] === undefined) {
  29713. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29714. }
  29715. }
  29716. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29717. // Create each face in turn.
  29718. for (var index = 0; index < normalsSource.length; index++) {
  29719. var normal = normalsSource[index];
  29720. // Get two vectors perpendicular to the face normal and to each other.
  29721. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29722. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29723. // Six indices (two triangles) per face.
  29724. var verticesLength = positions.length / 3;
  29725. indices.push(verticesLength);
  29726. indices.push(verticesLength + 1);
  29727. indices.push(verticesLength + 2);
  29728. indices.push(verticesLength);
  29729. indices.push(verticesLength + 2);
  29730. indices.push(verticesLength + 3);
  29731. // Four vertices per face.
  29732. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29733. positions.push(vertex.x, vertex.y, vertex.z);
  29734. normals.push(normal.x, normal.y, normal.z);
  29735. uvs.push(faceUV[index].z, faceUV[index].w);
  29736. if (faceColors) {
  29737. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29738. }
  29739. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29740. positions.push(vertex.x, vertex.y, vertex.z);
  29741. normals.push(normal.x, normal.y, normal.z);
  29742. uvs.push(faceUV[index].x, faceUV[index].w);
  29743. if (faceColors) {
  29744. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29745. }
  29746. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29747. positions.push(vertex.x, vertex.y, vertex.z);
  29748. normals.push(normal.x, normal.y, normal.z);
  29749. uvs.push(faceUV[index].x, faceUV[index].y);
  29750. if (faceColors) {
  29751. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29752. }
  29753. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29754. positions.push(vertex.x, vertex.y, vertex.z);
  29755. normals.push(normal.x, normal.y, normal.z);
  29756. uvs.push(faceUV[index].z, faceUV[index].y);
  29757. if (faceColors) {
  29758. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29759. }
  29760. }
  29761. // sides
  29762. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29763. // Result
  29764. var vertexData = new VertexData();
  29765. vertexData.indices = indices;
  29766. vertexData.positions = positions;
  29767. vertexData.normals = normals;
  29768. vertexData.uvs = uvs;
  29769. if (faceColors) {
  29770. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29771. vertexData.colors = totalColors;
  29772. }
  29773. return vertexData;
  29774. };
  29775. /**
  29776. * Creates the VertexData of the Sphere.
  29777. */
  29778. VertexData.CreateSphere = function (options) {
  29779. var segments = options.segments || 32;
  29780. var diameterX = options.diameterX || options.diameter || 1;
  29781. var diameterY = options.diameterY || options.diameter || 1;
  29782. var diameterZ = options.diameterZ || options.diameter || 1;
  29783. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29784. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29786. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29787. var totalZRotationSteps = 2 + segments;
  29788. var totalYRotationSteps = 2 * totalZRotationSteps;
  29789. var indices = [];
  29790. var positions = [];
  29791. var normals = [];
  29792. var uvs = [];
  29793. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29794. var normalizedZ = zRotationStep / totalZRotationSteps;
  29795. var angleZ = normalizedZ * Math.PI * slice;
  29796. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29797. var normalizedY = yRotationStep / totalYRotationSteps;
  29798. var angleY = normalizedY * Math.PI * 2 * arc;
  29799. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29800. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29801. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29802. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29803. var vertex = complete.multiply(radius);
  29804. var normal = complete.divide(radius).normalize();
  29805. positions.push(vertex.x, vertex.y, vertex.z);
  29806. normals.push(normal.x, normal.y, normal.z);
  29807. uvs.push(normalizedY, normalizedZ);
  29808. }
  29809. if (zRotationStep > 0) {
  29810. var verticesCount = positions.length / 3;
  29811. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29812. indices.push((firstIndex));
  29813. indices.push((firstIndex + 1));
  29814. indices.push(firstIndex + totalYRotationSteps + 1);
  29815. indices.push((firstIndex + totalYRotationSteps + 1));
  29816. indices.push((firstIndex + 1));
  29817. indices.push((firstIndex + totalYRotationSteps + 2));
  29818. }
  29819. }
  29820. }
  29821. // Sides
  29822. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29823. // Result
  29824. var vertexData = new VertexData();
  29825. vertexData.indices = indices;
  29826. vertexData.positions = positions;
  29827. vertexData.normals = normals;
  29828. vertexData.uvs = uvs;
  29829. return vertexData;
  29830. };
  29831. /**
  29832. * Creates the VertexData of the Cylinder or Cone.
  29833. */
  29834. VertexData.CreateCylinder = function (options) {
  29835. var height = options.height || 2;
  29836. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29837. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29838. var tessellation = options.tessellation || 24;
  29839. var subdivisions = options.subdivisions || 1;
  29840. var hasRings = options.hasRings ? true : false;
  29841. var enclose = options.enclose ? true : false;
  29842. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29843. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29844. var faceUV = options.faceUV || new Array(3);
  29845. var faceColors = options.faceColors;
  29846. // default face colors and UV if undefined
  29847. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29848. var ringNb = (hasRings) ? subdivisions : 1;
  29849. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29850. var f;
  29851. for (f = 0; f < surfaceNb; f++) {
  29852. if (faceColors && faceColors[f] === undefined) {
  29853. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29854. }
  29855. }
  29856. for (f = 0; f < surfaceNb; f++) {
  29857. if (faceUV && faceUV[f] === undefined) {
  29858. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29859. }
  29860. }
  29861. var indices = new Array();
  29862. var positions = new Array();
  29863. var normals = new Array();
  29864. var uvs = new Array();
  29865. var colors = new Array();
  29866. var angle_step = Math.PI * 2 * arc / tessellation;
  29867. var angle;
  29868. var h;
  29869. var radius;
  29870. var tan = (diameterBottom - diameterTop) / 2 / height;
  29871. var ringVertex = BABYLON.Vector3.Zero();
  29872. var ringNormal = BABYLON.Vector3.Zero();
  29873. var ringFirstVertex = BABYLON.Vector3.Zero();
  29874. var ringFirstNormal = BABYLON.Vector3.Zero();
  29875. var quadNormal = BABYLON.Vector3.Zero();
  29876. var Y = BABYLON.Axis.Y;
  29877. // positions, normals, uvs
  29878. var i;
  29879. var j;
  29880. var r;
  29881. var ringIdx = 1;
  29882. var s = 1; // surface index
  29883. var cs = 0;
  29884. var v = 0;
  29885. for (i = 0; i <= subdivisions; i++) {
  29886. h = i / subdivisions;
  29887. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29888. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29889. for (r = 0; r < ringIdx; r++) {
  29890. if (hasRings) {
  29891. s += r;
  29892. }
  29893. if (enclose) {
  29894. s += 2 * r;
  29895. }
  29896. for (j = 0; j <= tessellation; j++) {
  29897. angle = j * angle_step;
  29898. // position
  29899. ringVertex.x = Math.cos(-angle) * radius;
  29900. ringVertex.y = -height / 2 + h * height;
  29901. ringVertex.z = Math.sin(-angle) * radius;
  29902. // normal
  29903. if (diameterTop === 0 && i === subdivisions) {
  29904. // if no top cap, reuse former normals
  29905. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29906. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29907. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29908. }
  29909. else {
  29910. ringNormal.x = ringVertex.x;
  29911. ringNormal.z = ringVertex.z;
  29912. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29913. ringNormal.normalize();
  29914. }
  29915. // keep first ring vertex values for enclose
  29916. if (j === 0) {
  29917. ringFirstVertex.copyFrom(ringVertex);
  29918. ringFirstNormal.copyFrom(ringNormal);
  29919. }
  29920. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29921. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29922. if (hasRings) {
  29923. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29924. }
  29925. else {
  29926. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29927. }
  29928. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29929. if (faceColors) {
  29930. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29931. }
  29932. }
  29933. // if enclose, add four vertices and their dedicated normals
  29934. if (arc !== 1 && enclose) {
  29935. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29936. positions.push(0, ringVertex.y, 0);
  29937. positions.push(0, ringVertex.y, 0);
  29938. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29939. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29940. quadNormal.normalize();
  29941. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29942. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29943. quadNormal.normalize();
  29944. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29945. if (hasRings) {
  29946. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29947. }
  29948. else {
  29949. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29950. }
  29951. uvs.push(faceUV[s + 1].x, v);
  29952. uvs.push(faceUV[s + 1].z, v);
  29953. if (hasRings) {
  29954. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29955. }
  29956. else {
  29957. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29958. }
  29959. uvs.push(faceUV[s + 2].x, v);
  29960. uvs.push(faceUV[s + 2].z, v);
  29961. if (faceColors) {
  29962. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29963. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29964. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29965. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29966. }
  29967. }
  29968. if (cs !== s) {
  29969. cs = s;
  29970. }
  29971. }
  29972. }
  29973. // indices
  29974. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29975. var s;
  29976. i = 0;
  29977. for (s = 0; s < subdivisions; s++) {
  29978. var i0 = 0;
  29979. var i1 = 0;
  29980. var i2 = 0;
  29981. var i3 = 0;
  29982. for (j = 0; j < tessellation; j++) {
  29983. i0 = i * (e + 1) + j;
  29984. i1 = (i + 1) * (e + 1) + j;
  29985. i2 = i * (e + 1) + (j + 1);
  29986. i3 = (i + 1) * (e + 1) + (j + 1);
  29987. indices.push(i0, i1, i2);
  29988. indices.push(i3, i2, i1);
  29989. }
  29990. if (arc !== 1 && enclose) {
  29991. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29992. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29993. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29994. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29995. }
  29996. i = (hasRings) ? (i + 2) : (i + 1);
  29997. }
  29998. // Caps
  29999. var createCylinderCap = function (isTop) {
  30000. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30001. if (radius === 0) {
  30002. return;
  30003. }
  30004. // Cap positions, normals & uvs
  30005. var angle;
  30006. var circleVector;
  30007. var i;
  30008. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30009. var c = null;
  30010. if (faceColors) {
  30011. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30012. }
  30013. // cap center
  30014. var vbase = positions.length / 3;
  30015. var offset = isTop ? height / 2 : -height / 2;
  30016. var center = new BABYLON.Vector3(0, offset, 0);
  30017. positions.push(center.x, center.y, center.z);
  30018. normals.push(0, isTop ? 1 : -1, 0);
  30019. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30020. if (c) {
  30021. colors.push(c.r, c.g, c.b, c.a);
  30022. }
  30023. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30024. for (i = 0; i <= tessellation; i++) {
  30025. angle = Math.PI * 2 * i * arc / tessellation;
  30026. var cos = Math.cos(-angle);
  30027. var sin = Math.sin(-angle);
  30028. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30029. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30030. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30031. normals.push(0, isTop ? 1 : -1, 0);
  30032. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30033. if (c) {
  30034. colors.push(c.r, c.g, c.b, c.a);
  30035. }
  30036. }
  30037. // Cap indices
  30038. for (i = 0; i < tessellation; i++) {
  30039. if (!isTop) {
  30040. indices.push(vbase);
  30041. indices.push(vbase + (i + 1));
  30042. indices.push(vbase + (i + 2));
  30043. }
  30044. else {
  30045. indices.push(vbase);
  30046. indices.push(vbase + (i + 2));
  30047. indices.push(vbase + (i + 1));
  30048. }
  30049. }
  30050. };
  30051. // add caps to geometry
  30052. createCylinderCap(false);
  30053. createCylinderCap(true);
  30054. // Sides
  30055. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30056. var vertexData = new VertexData();
  30057. vertexData.indices = indices;
  30058. vertexData.positions = positions;
  30059. vertexData.normals = normals;
  30060. vertexData.uvs = uvs;
  30061. if (faceColors) {
  30062. vertexData.colors = colors;
  30063. }
  30064. return vertexData;
  30065. };
  30066. /**
  30067. * Creates the VertexData of the Torus.
  30068. */
  30069. VertexData.CreateTorus = function (options) {
  30070. var indices = [];
  30071. var positions = [];
  30072. var normals = [];
  30073. var uvs = [];
  30074. var diameter = options.diameter || 1;
  30075. var thickness = options.thickness || 0.5;
  30076. var tessellation = options.tessellation || 16;
  30077. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30078. var stride = tessellation + 1;
  30079. for (var i = 0; i <= tessellation; i++) {
  30080. var u = i / tessellation;
  30081. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30082. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30083. for (var j = 0; j <= tessellation; j++) {
  30084. var v = 1 - j / tessellation;
  30085. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30086. var dx = Math.cos(innerAngle);
  30087. var dy = Math.sin(innerAngle);
  30088. // Create a vertex.
  30089. var normal = new BABYLON.Vector3(dx, dy, 0);
  30090. var position = normal.scale(thickness / 2);
  30091. var textureCoordinate = new BABYLON.Vector2(u, v);
  30092. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30093. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30094. positions.push(position.x, position.y, position.z);
  30095. normals.push(normal.x, normal.y, normal.z);
  30096. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30097. // And create indices for two triangles.
  30098. var nextI = (i + 1) % stride;
  30099. var nextJ = (j + 1) % stride;
  30100. indices.push(i * stride + j);
  30101. indices.push(i * stride + nextJ);
  30102. indices.push(nextI * stride + j);
  30103. indices.push(i * stride + nextJ);
  30104. indices.push(nextI * stride + nextJ);
  30105. indices.push(nextI * stride + j);
  30106. }
  30107. }
  30108. // Sides
  30109. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30110. // Result
  30111. var vertexData = new VertexData();
  30112. vertexData.indices = indices;
  30113. vertexData.positions = positions;
  30114. vertexData.normals = normals;
  30115. vertexData.uvs = uvs;
  30116. return vertexData;
  30117. };
  30118. /**
  30119. * Creates the VertexData of the LineSystem.
  30120. */
  30121. VertexData.CreateLineSystem = function (options) {
  30122. var indices = [];
  30123. var positions = [];
  30124. var lines = options.lines;
  30125. var colors = options.colors;
  30126. var vertexColors = [];
  30127. var idx = 0;
  30128. for (var l = 0; l < lines.length; l++) {
  30129. var points = lines[l];
  30130. for (var index = 0; index < points.length; index++) {
  30131. positions.push(points[index].x, points[index].y, points[index].z);
  30132. if (colors) {
  30133. var color = colors[l];
  30134. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30135. }
  30136. if (index > 0) {
  30137. indices.push(idx - 1);
  30138. indices.push(idx);
  30139. }
  30140. idx++;
  30141. }
  30142. }
  30143. var vertexData = new VertexData();
  30144. vertexData.indices = indices;
  30145. vertexData.positions = positions;
  30146. if (colors) {
  30147. vertexData.colors = vertexColors;
  30148. }
  30149. return vertexData;
  30150. };
  30151. /**
  30152. * Create the VertexData of the DashedLines.
  30153. */
  30154. VertexData.CreateDashedLines = function (options) {
  30155. var dashSize = options.dashSize || 3;
  30156. var gapSize = options.gapSize || 1;
  30157. var dashNb = options.dashNb || 200;
  30158. var points = options.points;
  30159. var positions = new Array();
  30160. var indices = new Array();
  30161. var curvect = BABYLON.Vector3.Zero();
  30162. var lg = 0;
  30163. var nb = 0;
  30164. var shft = 0;
  30165. var dashshft = 0;
  30166. var curshft = 0;
  30167. var idx = 0;
  30168. var i = 0;
  30169. for (i = 0; i < points.length - 1; i++) {
  30170. points[i + 1].subtractToRef(points[i], curvect);
  30171. lg += curvect.length();
  30172. }
  30173. shft = lg / dashNb;
  30174. dashshft = dashSize * shft / (dashSize + gapSize);
  30175. for (i = 0; i < points.length - 1; i++) {
  30176. points[i + 1].subtractToRef(points[i], curvect);
  30177. nb = Math.floor(curvect.length() / shft);
  30178. curvect.normalize();
  30179. for (var j = 0; j < nb; j++) {
  30180. curshft = shft * j;
  30181. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30182. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30183. indices.push(idx, idx + 1);
  30184. idx += 2;
  30185. }
  30186. }
  30187. // Result
  30188. var vertexData = new VertexData();
  30189. vertexData.positions = positions;
  30190. vertexData.indices = indices;
  30191. return vertexData;
  30192. };
  30193. /**
  30194. * Creates the VertexData of the Ground.
  30195. */
  30196. VertexData.CreateGround = function (options) {
  30197. var indices = [];
  30198. var positions = [];
  30199. var normals = [];
  30200. var uvs = [];
  30201. var row, col;
  30202. var width = options.width || 1;
  30203. var height = options.height || 1;
  30204. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30205. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30206. for (row = 0; row <= subdivisionsY; row++) {
  30207. for (col = 0; col <= subdivisionsX; col++) {
  30208. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30209. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30210. positions.push(position.x, position.y, position.z);
  30211. normals.push(normal.x, normal.y, normal.z);
  30212. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30213. }
  30214. }
  30215. for (row = 0; row < subdivisionsY; row++) {
  30216. for (col = 0; col < subdivisionsX; col++) {
  30217. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30218. indices.push(col + 1 + row * (subdivisionsX + 1));
  30219. indices.push(col + row * (subdivisionsX + 1));
  30220. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30221. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30222. indices.push(col + row * (subdivisionsX + 1));
  30223. }
  30224. }
  30225. // Result
  30226. var vertexData = new VertexData();
  30227. vertexData.indices = indices;
  30228. vertexData.positions = positions;
  30229. vertexData.normals = normals;
  30230. vertexData.uvs = uvs;
  30231. return vertexData;
  30232. };
  30233. /**
  30234. * Creates the VertexData of the TiledGround.
  30235. */
  30236. VertexData.CreateTiledGround = function (options) {
  30237. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30238. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30239. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30240. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30241. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30242. var precision = options.precision || { w: 1, h: 1 };
  30243. var indices = new Array();
  30244. var positions = new Array();
  30245. var normals = new Array();
  30246. var uvs = new Array();
  30247. var row, col, tileRow, tileCol;
  30248. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30249. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30250. precision.w = (precision.w < 1) ? 1 : precision.w;
  30251. precision.h = (precision.h < 1) ? 1 : precision.h;
  30252. var tileSize = {
  30253. 'w': (xmax - xmin) / subdivisions.w,
  30254. 'h': (zmax - zmin) / subdivisions.h
  30255. };
  30256. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30257. // Indices
  30258. var base = positions.length / 3;
  30259. var rowLength = precision.w + 1;
  30260. for (row = 0; row < precision.h; row++) {
  30261. for (col = 0; col < precision.w; col++) {
  30262. var square = [
  30263. base + col + row * rowLength,
  30264. base + (col + 1) + row * rowLength,
  30265. base + (col + 1) + (row + 1) * rowLength,
  30266. base + col + (row + 1) * rowLength
  30267. ];
  30268. indices.push(square[1]);
  30269. indices.push(square[2]);
  30270. indices.push(square[3]);
  30271. indices.push(square[0]);
  30272. indices.push(square[1]);
  30273. indices.push(square[3]);
  30274. }
  30275. }
  30276. // Position, normals and uvs
  30277. var position = BABYLON.Vector3.Zero();
  30278. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30279. for (row = 0; row <= precision.h; row++) {
  30280. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30281. for (col = 0; col <= precision.w; col++) {
  30282. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30283. position.y = 0;
  30284. positions.push(position.x, position.y, position.z);
  30285. normals.push(normal.x, normal.y, normal.z);
  30286. uvs.push(col / precision.w, row / precision.h);
  30287. }
  30288. }
  30289. }
  30290. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30291. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30292. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30293. }
  30294. }
  30295. // Result
  30296. var vertexData = new VertexData();
  30297. vertexData.indices = indices;
  30298. vertexData.positions = positions;
  30299. vertexData.normals = normals;
  30300. vertexData.uvs = uvs;
  30301. return vertexData;
  30302. };
  30303. /**
  30304. * Creates the VertexData of the Ground designed from a heightmap.
  30305. */
  30306. VertexData.CreateGroundFromHeightMap = function (options) {
  30307. var indices = [];
  30308. var positions = [];
  30309. var normals = [];
  30310. var uvs = [];
  30311. var row, col;
  30312. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30313. // Vertices
  30314. for (row = 0; row <= options.subdivisions; row++) {
  30315. for (col = 0; col <= options.subdivisions; col++) {
  30316. 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));
  30317. // Compute height
  30318. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30319. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30320. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30321. var r = options.buffer[pos] / 255.0;
  30322. var g = options.buffer[pos + 1] / 255.0;
  30323. var b = options.buffer[pos + 2] / 255.0;
  30324. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30325. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30326. // Add vertex
  30327. positions.push(position.x, position.y, position.z);
  30328. normals.push(0, 0, 0);
  30329. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30330. }
  30331. }
  30332. // Indices
  30333. for (row = 0; row < options.subdivisions; row++) {
  30334. for (col = 0; col < options.subdivisions; col++) {
  30335. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30336. indices.push(col + 1 + row * (options.subdivisions + 1));
  30337. indices.push(col + row * (options.subdivisions + 1));
  30338. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30339. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30340. indices.push(col + row * (options.subdivisions + 1));
  30341. }
  30342. }
  30343. // Normals
  30344. VertexData.ComputeNormals(positions, indices, normals);
  30345. // Result
  30346. var vertexData = new VertexData();
  30347. vertexData.indices = indices;
  30348. vertexData.positions = positions;
  30349. vertexData.normals = normals;
  30350. vertexData.uvs = uvs;
  30351. return vertexData;
  30352. };
  30353. /**
  30354. * Creates the VertexData of the Plane.
  30355. */
  30356. VertexData.CreatePlane = function (options) {
  30357. var indices = [];
  30358. var positions = [];
  30359. var normals = [];
  30360. var uvs = [];
  30361. var width = options.width || options.size || 1;
  30362. var height = options.height || options.size || 1;
  30363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30364. // Vertices
  30365. var halfWidth = width / 2.0;
  30366. var halfHeight = height / 2.0;
  30367. positions.push(-halfWidth, -halfHeight, 0);
  30368. normals.push(0, 0, -1.0);
  30369. uvs.push(0.0, 0.0);
  30370. positions.push(halfWidth, -halfHeight, 0);
  30371. normals.push(0, 0, -1.0);
  30372. uvs.push(1.0, 0.0);
  30373. positions.push(halfWidth, halfHeight, 0);
  30374. normals.push(0, 0, -1.0);
  30375. uvs.push(1.0, 1.0);
  30376. positions.push(-halfWidth, halfHeight, 0);
  30377. normals.push(0, 0, -1.0);
  30378. uvs.push(0.0, 1.0);
  30379. // Indices
  30380. indices.push(0);
  30381. indices.push(1);
  30382. indices.push(2);
  30383. indices.push(0);
  30384. indices.push(2);
  30385. indices.push(3);
  30386. // Sides
  30387. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30388. // Result
  30389. var vertexData = new VertexData();
  30390. vertexData.indices = indices;
  30391. vertexData.positions = positions;
  30392. vertexData.normals = normals;
  30393. vertexData.uvs = uvs;
  30394. return vertexData;
  30395. };
  30396. /**
  30397. * Creates the VertexData of the Disc or regular Polygon.
  30398. */
  30399. VertexData.CreateDisc = function (options) {
  30400. var positions = new Array();
  30401. var indices = new Array();
  30402. var normals = new Array();
  30403. var uvs = new Array();
  30404. var radius = options.radius || 0.5;
  30405. var tessellation = options.tessellation || 64;
  30406. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30407. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30408. // positions and uvs
  30409. positions.push(0, 0, 0); // disc center first
  30410. uvs.push(0.5, 0.5);
  30411. var theta = Math.PI * 2 * arc;
  30412. var step = theta / tessellation;
  30413. for (var a = 0; a < theta; a += step) {
  30414. var x = Math.cos(a);
  30415. var y = Math.sin(a);
  30416. var u = (x + 1) / 2;
  30417. var v = (1 - y) / 2;
  30418. positions.push(radius * x, radius * y, 0);
  30419. uvs.push(u, v);
  30420. }
  30421. if (arc === 1) {
  30422. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30423. uvs.push(uvs[2], uvs[3]);
  30424. }
  30425. //indices
  30426. var vertexNb = positions.length / 3;
  30427. for (var i = 1; i < vertexNb - 1; i++) {
  30428. indices.push(i + 1, 0, i);
  30429. }
  30430. // result
  30431. VertexData.ComputeNormals(positions, indices, normals);
  30432. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30433. var vertexData = new VertexData();
  30434. vertexData.indices = indices;
  30435. vertexData.positions = positions;
  30436. vertexData.normals = normals;
  30437. vertexData.uvs = uvs;
  30438. return vertexData;
  30439. };
  30440. /**
  30441. * Re-creates the VertexData of the Polygon for sideOrientation.
  30442. */
  30443. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30444. var faceUV = fUV || new Array(3);
  30445. var faceColors = fColors;
  30446. var colors = [];
  30447. // default face colors and UV if undefined
  30448. for (var f = 0; f < 3; f++) {
  30449. if (faceUV[f] === undefined) {
  30450. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30451. }
  30452. if (faceColors && faceColors[f] === undefined) {
  30453. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30454. }
  30455. }
  30456. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30457. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30458. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30459. var indices = polygon.getIndices();
  30460. // set face colours and textures
  30461. var idx = 0;
  30462. var face = 0;
  30463. for (var index = 0; index < normals.length; index += 3) {
  30464. //Edge Face no. 1
  30465. if (Math.abs(normals[index + 1]) < 0.001) {
  30466. face = 1;
  30467. }
  30468. //Top Face no. 0
  30469. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30470. face = 0;
  30471. }
  30472. //Bottom Face no. 2
  30473. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30474. face = 2;
  30475. }
  30476. idx = index / 3;
  30477. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30478. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30479. if (faceColors) {
  30480. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30481. }
  30482. }
  30483. // sides
  30484. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30485. // Result
  30486. var vertexData = new VertexData();
  30487. vertexData.indices = indices;
  30488. vertexData.positions = positions;
  30489. vertexData.normals = normals;
  30490. vertexData.uvs = uvs;
  30491. if (faceColors) {
  30492. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30493. vertexData.colors = totalColors;
  30494. }
  30495. return vertexData;
  30496. };
  30497. /**
  30498. * Creates the VertexData of the IcoSphere.
  30499. */
  30500. VertexData.CreateIcoSphere = function (options) {
  30501. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30502. var radius = options.radius || 1;
  30503. var flat = (options.flat === undefined) ? true : options.flat;
  30504. var subdivisions = options.subdivisions || 4;
  30505. var radiusX = options.radiusX || radius;
  30506. var radiusY = options.radiusY || radius;
  30507. var radiusZ = options.radiusZ || radius;
  30508. var t = (1 + Math.sqrt(5)) / 2;
  30509. // 12 vertex x,y,z
  30510. var ico_vertices = [
  30511. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30512. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30513. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30514. ];
  30515. // index of 3 vertex makes a face of icopshere
  30516. var ico_indices = [
  30517. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30518. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30519. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30520. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30521. ];
  30522. // vertex for uv have aliased position, not for UV
  30523. var vertices_unalias_id = [
  30524. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30525. // vertex alias
  30526. 0,
  30527. 2,
  30528. 3,
  30529. 3,
  30530. 3,
  30531. 4,
  30532. 7,
  30533. 8,
  30534. 9,
  30535. 9,
  30536. 10,
  30537. 11 // 23: B + 12
  30538. ];
  30539. // uv as integer step (not pixels !)
  30540. var ico_vertexuv = [
  30541. 5, 1, 3, 1, 6, 4, 0, 0,
  30542. 5, 3, 4, 2, 2, 2, 4, 0,
  30543. 2, 0, 1, 1, 6, 0, 6, 2,
  30544. // vertex alias (for same vertex on different faces)
  30545. 0, 4,
  30546. 3, 3,
  30547. 4, 4,
  30548. 3, 1,
  30549. 4, 2,
  30550. 4, 4,
  30551. 0, 2,
  30552. 1, 1,
  30553. 2, 2,
  30554. 3, 3,
  30555. 1, 3,
  30556. 2, 4 // 23: B + 12
  30557. ];
  30558. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30559. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30560. // First island of uv mapping
  30561. // v = 4h 3+ 2
  30562. // v = 3h 9+ 4
  30563. // v = 2h 9+ 5 B
  30564. // v = 1h 9 1 0
  30565. // v = 0h 3 8 7 A
  30566. // u = 0 1 2 3 4 5 6 *a
  30567. // Second island of uv mapping
  30568. // v = 4h 0+ B+ 4+
  30569. // v = 3h A+ 2+
  30570. // v = 2h 7+ 6 3+
  30571. // v = 1h 8+ 3+
  30572. // v = 0h
  30573. // u = 0 1 2 3 4 5 6 *a
  30574. // Face layout on texture UV mapping
  30575. // ============
  30576. // \ 4 /\ 16 / ======
  30577. // \ / \ / /\ 11 /
  30578. // \/ 7 \/ / \ /
  30579. // ======= / 10 \/
  30580. // /\ 17 /\ =======
  30581. // / \ / \ \ 15 /\
  30582. // / 8 \/ 12 \ \ / \
  30583. // ============ \/ 6 \
  30584. // \ 18 /\ ============
  30585. // \ / \ \ 5 /\ 0 /
  30586. // \/ 13 \ \ / \ /
  30587. // ======= \/ 1 \/
  30588. // =============
  30589. // /\ 19 /\ 2 /\
  30590. // / \ / \ / \
  30591. // / 14 \/ 9 \/ 3 \
  30592. // ===================
  30593. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30594. var ustep = 138 / 1024;
  30595. var vstep = 239 / 1024;
  30596. var uoffset = 60 / 1024;
  30597. var voffset = 26 / 1024;
  30598. // Second island should have margin, not to touch the first island
  30599. // avoid any borderline artefact in pixel rounding
  30600. var island_u_offset = -40 / 1024;
  30601. var island_v_offset = +20 / 1024;
  30602. // face is either island 0 or 1 :
  30603. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30604. var island = [
  30605. 0, 0, 0, 0, 1,
  30606. 0, 0, 1, 1, 0,
  30607. 0, 0, 1, 1, 0,
  30608. 0, 1, 1, 1, 0 // 15 - 19
  30609. ];
  30610. var indices = new Array();
  30611. var positions = new Array();
  30612. var normals = new Array();
  30613. var uvs = new Array();
  30614. var current_indice = 0;
  30615. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30616. var face_vertex_pos = new Array(3);
  30617. var face_vertex_uv = new Array(3);
  30618. var v012;
  30619. for (v012 = 0; v012 < 3; v012++) {
  30620. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30621. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30622. }
  30623. // create all with normals
  30624. for (var face = 0; face < 20; face++) {
  30625. // 3 vertex per face
  30626. for (v012 = 0; v012 < 3; v012++) {
  30627. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30628. var v_id = ico_indices[3 * face + v012];
  30629. // vertex have 3D position (x,y,z)
  30630. 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]);
  30631. // Normalize to get normal, then scale to radius
  30632. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30633. // uv Coordinates from vertex ID
  30634. 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);
  30635. }
  30636. // Subdivide the face (interpolate pos, norm, uv)
  30637. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30638. // - norm is linear interpolation of vertex corner normal
  30639. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30640. // - uv is linear interpolation
  30641. //
  30642. // Topology is as below for sub-divide by 2
  30643. // vertex shown as v0,v1,v2
  30644. // interp index is i1 to progress in range [v0,v1[
  30645. // interp index is i2 to progress in range [v0,v2[
  30646. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30647. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30648. //
  30649. //
  30650. // i2 v2
  30651. // ^ ^
  30652. // / / \
  30653. // / / \
  30654. // / / \
  30655. // / / (0,1) \
  30656. // / #---------\
  30657. // / / \ (0,0)'/ \
  30658. // / / \ / \
  30659. // / / \ / \
  30660. // / / (0,0) \ / (1,0) \
  30661. // / #---------#---------\
  30662. // v0 v1
  30663. //
  30664. // --------------------> i1
  30665. //
  30666. // interp of (i1,i2):
  30667. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30668. // along i1 : lerp(x0,x1, i1/(S-i2))
  30669. //
  30670. // centroid of triangle is needed to get help normal computation
  30671. // (c1,c2) are used for centroid location
  30672. var interp_vertex = function (i1, i2, c1, c2) {
  30673. // vertex is interpolated from
  30674. // - face_vertex_pos[0..2]
  30675. // - face_vertex_uv[0..2]
  30676. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30677. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30678. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30679. pos_interp.normalize();
  30680. var vertex_normal;
  30681. if (flat) {
  30682. // in flat mode, recalculate normal as face centroid normal
  30683. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30684. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30685. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30686. }
  30687. else {
  30688. // in smooth mode, recalculate normal from each single vertex position
  30689. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30690. }
  30691. // Vertex normal need correction due to X,Y,Z radius scaling
  30692. vertex_normal.x /= radiusX;
  30693. vertex_normal.y /= radiusY;
  30694. vertex_normal.z /= radiusZ;
  30695. vertex_normal.normalize();
  30696. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30697. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30698. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30699. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30700. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30701. uvs.push(uv_interp.x, uv_interp.y);
  30702. // push each vertex has member of a face
  30703. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30704. indices.push(current_indice);
  30705. current_indice++;
  30706. };
  30707. for (var i2 = 0; i2 < subdivisions; i2++) {
  30708. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30709. // face : (i1,i2) for /\ :
  30710. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30711. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30712. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30713. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30714. if (i1 + i2 + 1 < subdivisions) {
  30715. // face : (i1,i2)' for \/ :
  30716. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30717. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30718. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30719. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30720. }
  30721. }
  30722. }
  30723. }
  30724. // Sides
  30725. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30726. // Result
  30727. var vertexData = new VertexData();
  30728. vertexData.indices = indices;
  30729. vertexData.positions = positions;
  30730. vertexData.normals = normals;
  30731. vertexData.uvs = uvs;
  30732. return vertexData;
  30733. };
  30734. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30735. /**
  30736. * Creates the VertexData of the Polyhedron.
  30737. */
  30738. VertexData.CreatePolyhedron = function (options) {
  30739. // provided polyhedron types :
  30740. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30741. // 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)
  30742. var polyhedra = [];
  30743. 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]] };
  30744. 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]] };
  30745. polyhedra[2] = {
  30746. 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]],
  30747. 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]]
  30748. };
  30749. polyhedra[3] = {
  30750. 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]],
  30751. 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]]
  30752. };
  30753. polyhedra[4] = {
  30754. 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]],
  30755. 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]]
  30756. };
  30757. 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]] };
  30758. 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]] };
  30759. 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]] };
  30760. 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]] };
  30761. 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]] };
  30762. 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]] };
  30763. 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]] };
  30764. 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]] };
  30765. 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]] };
  30766. polyhedra[14] = {
  30767. 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]],
  30768. 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]]
  30769. };
  30770. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30771. var size = options.size;
  30772. var sizeX = options.sizeX || size || 1;
  30773. var sizeY = options.sizeY || size || 1;
  30774. var sizeZ = options.sizeZ || size || 1;
  30775. var data = options.custom || polyhedra[type];
  30776. var nbfaces = data.face.length;
  30777. var faceUV = options.faceUV || new Array(nbfaces);
  30778. var faceColors = options.faceColors;
  30779. var flat = (options.flat === undefined) ? true : options.flat;
  30780. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30781. var positions = new Array();
  30782. var indices = new Array();
  30783. var normals = new Array();
  30784. var uvs = new Array();
  30785. var colors = new Array();
  30786. var index = 0;
  30787. var faceIdx = 0; // face cursor in the array "indexes"
  30788. var indexes = new Array();
  30789. var i = 0;
  30790. var f = 0;
  30791. var u, v, ang, x, y, tmp;
  30792. // default face colors and UV if undefined
  30793. if (flat) {
  30794. for (f = 0; f < nbfaces; f++) {
  30795. if (faceColors && faceColors[f] === undefined) {
  30796. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30797. }
  30798. if (faceUV && faceUV[f] === undefined) {
  30799. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30800. }
  30801. }
  30802. }
  30803. if (!flat) {
  30804. for (i = 0; i < data.vertex.length; i++) {
  30805. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30806. uvs.push(0, 0);
  30807. }
  30808. for (f = 0; f < nbfaces; f++) {
  30809. for (i = 0; i < data.face[f].length - 2; i++) {
  30810. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30811. }
  30812. }
  30813. }
  30814. else {
  30815. for (f = 0; f < nbfaces; f++) {
  30816. var fl = data.face[f].length; // number of vertices of the current face
  30817. ang = 2 * Math.PI / fl;
  30818. x = 0.5 * Math.tan(ang / 2);
  30819. y = 0.5;
  30820. // positions, uvs, colors
  30821. for (i = 0; i < fl; i++) {
  30822. // positions
  30823. 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);
  30824. indexes.push(index);
  30825. index++;
  30826. // uvs
  30827. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30828. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30829. uvs.push(u, v);
  30830. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30831. y = x * Math.sin(ang) + y * Math.cos(ang);
  30832. x = tmp;
  30833. // colors
  30834. if (faceColors) {
  30835. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30836. }
  30837. }
  30838. // indices from indexes
  30839. for (i = 0; i < fl - 2; i++) {
  30840. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30841. }
  30842. faceIdx += fl;
  30843. }
  30844. }
  30845. VertexData.ComputeNormals(positions, indices, normals);
  30846. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30847. var vertexData = new VertexData();
  30848. vertexData.positions = positions;
  30849. vertexData.indices = indices;
  30850. vertexData.normals = normals;
  30851. vertexData.uvs = uvs;
  30852. if (faceColors && flat) {
  30853. vertexData.colors = colors;
  30854. }
  30855. return vertexData;
  30856. };
  30857. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30858. /**
  30859. * Creates the VertexData of the Torus Knot.
  30860. */
  30861. VertexData.CreateTorusKnot = function (options) {
  30862. var indices = new Array();
  30863. var positions = new Array();
  30864. var normals = new Array();
  30865. var uvs = new Array();
  30866. var radius = options.radius || 2;
  30867. var tube = options.tube || 0.5;
  30868. var radialSegments = options.radialSegments || 32;
  30869. var tubularSegments = options.tubularSegments || 32;
  30870. var p = options.p || 2;
  30871. var q = options.q || 3;
  30872. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30873. // Helper
  30874. var getPos = function (angle) {
  30875. var cu = Math.cos(angle);
  30876. var su = Math.sin(angle);
  30877. var quOverP = q / p * angle;
  30878. var cs = Math.cos(quOverP);
  30879. var tx = radius * (2 + cs) * 0.5 * cu;
  30880. var ty = radius * (2 + cs) * su * 0.5;
  30881. var tz = radius * Math.sin(quOverP) * 0.5;
  30882. return new BABYLON.Vector3(tx, ty, tz);
  30883. };
  30884. // Vertices
  30885. var i;
  30886. var j;
  30887. for (i = 0; i <= radialSegments; i++) {
  30888. var modI = i % radialSegments;
  30889. var u = modI / radialSegments * 2 * p * Math.PI;
  30890. var p1 = getPos(u);
  30891. var p2 = getPos(u + 0.01);
  30892. var tang = p2.subtract(p1);
  30893. var n = p2.add(p1);
  30894. var bitan = BABYLON.Vector3.Cross(tang, n);
  30895. n = BABYLON.Vector3.Cross(bitan, tang);
  30896. bitan.normalize();
  30897. n.normalize();
  30898. for (j = 0; j < tubularSegments; j++) {
  30899. var modJ = j % tubularSegments;
  30900. var v = modJ / tubularSegments * 2 * Math.PI;
  30901. var cx = -tube * Math.cos(v);
  30902. var cy = tube * Math.sin(v);
  30903. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30904. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30905. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30906. uvs.push(i / radialSegments);
  30907. uvs.push(j / tubularSegments);
  30908. }
  30909. }
  30910. for (i = 0; i < radialSegments; i++) {
  30911. for (j = 0; j < tubularSegments; j++) {
  30912. var jNext = (j + 1) % tubularSegments;
  30913. var a = i * tubularSegments + j;
  30914. var b = (i + 1) * tubularSegments + j;
  30915. var c = (i + 1) * tubularSegments + jNext;
  30916. var d = i * tubularSegments + jNext;
  30917. indices.push(d);
  30918. indices.push(b);
  30919. indices.push(a);
  30920. indices.push(d);
  30921. indices.push(c);
  30922. indices.push(b);
  30923. }
  30924. }
  30925. // Normals
  30926. VertexData.ComputeNormals(positions, indices, normals);
  30927. // Sides
  30928. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30929. // Result
  30930. var vertexData = new VertexData();
  30931. vertexData.indices = indices;
  30932. vertexData.positions = positions;
  30933. vertexData.normals = normals;
  30934. vertexData.uvs = uvs;
  30935. return vertexData;
  30936. };
  30937. // Tools
  30938. /**
  30939. * @param {any} - positions (number[] or Float32Array)
  30940. * @param {any} - indices (number[] or Uint16Array)
  30941. * @param {any} - normals (number[] or Float32Array)
  30942. * options (optional) :
  30943. * facetPositions : optional array of facet positions (vector3)
  30944. * facetNormals : optional array of facet normals (vector3)
  30945. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30946. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30947. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30948. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30949. * bInfo : optional bounding info, required for facetPartitioning computation
  30950. * useRightHandedSystem: optional boolean to for right handed system computation
  30951. * depthSort : optional boolean to enable the facet depth sort computation
  30952. * distanceTo : optional Vector3 to compute the facet depth from this location
  30953. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30954. */
  30955. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30956. // temporary scalar variables
  30957. var index = 0; // facet index
  30958. var p1p2x = 0.0; // p1p2 vector x coordinate
  30959. var p1p2y = 0.0; // p1p2 vector y coordinate
  30960. var p1p2z = 0.0; // p1p2 vector z coordinate
  30961. var p3p2x = 0.0; // p3p2 vector x coordinate
  30962. var p3p2y = 0.0; // p3p2 vector y coordinate
  30963. var p3p2z = 0.0; // p3p2 vector z coordinate
  30964. var faceNormalx = 0.0; // facet normal x coordinate
  30965. var faceNormaly = 0.0; // facet normal y coordinate
  30966. var faceNormalz = 0.0; // facet normal z coordinate
  30967. var length = 0.0; // facet normal length before normalization
  30968. var v1x = 0; // vector1 x index in the positions array
  30969. var v1y = 0; // vector1 y index in the positions array
  30970. var v1z = 0; // vector1 z index in the positions array
  30971. var v2x = 0; // vector2 x index in the positions array
  30972. var v2y = 0; // vector2 y index in the positions array
  30973. var v2z = 0; // vector2 z index in the positions array
  30974. var v3x = 0; // vector3 x index in the positions array
  30975. var v3y = 0; // vector3 y index in the positions array
  30976. var v3z = 0; // vector3 z index in the positions array
  30977. var computeFacetNormals = false;
  30978. var computeFacetPositions = false;
  30979. var computeFacetPartitioning = false;
  30980. var computeDepthSort = false;
  30981. var faceNormalSign = 1;
  30982. var ratio = 0;
  30983. var distanceTo = null;
  30984. if (options) {
  30985. computeFacetNormals = (options.facetNormals) ? true : false;
  30986. computeFacetPositions = (options.facetPositions) ? true : false;
  30987. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30988. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30989. ratio = options.ratio || 0;
  30990. computeDepthSort = (options.depthSort) ? true : false;
  30991. distanceTo = (options.distanceTo);
  30992. if (computeDepthSort) {
  30993. if (distanceTo === undefined) {
  30994. distanceTo = BABYLON.Vector3.Zero();
  30995. }
  30996. var depthSortedFacets = options.depthSortedFacets;
  30997. }
  30998. }
  30999. // facetPartitioning reinit if needed
  31000. var xSubRatio = 0;
  31001. var ySubRatio = 0;
  31002. var zSubRatio = 0;
  31003. var subSq = 0;
  31004. if (computeFacetPartitioning && options && options.bbSize) {
  31005. var ox = 0; // X partitioning index for facet position
  31006. var oy = 0; // Y partinioning index for facet position
  31007. var oz = 0; // Z partinioning index for facet position
  31008. var b1x = 0; // X partitioning index for facet v1 vertex
  31009. var b1y = 0; // Y partitioning index for facet v1 vertex
  31010. var b1z = 0; // z partitioning index for facet v1 vertex
  31011. var b2x = 0; // X partitioning index for facet v2 vertex
  31012. var b2y = 0; // Y partitioning index for facet v2 vertex
  31013. var b2z = 0; // Z partitioning index for facet v2 vertex
  31014. var b3x = 0; // X partitioning index for facet v3 vertex
  31015. var b3y = 0; // Y partitioning index for facet v3 vertex
  31016. var b3z = 0; // Z partitioning index for facet v3 vertex
  31017. var block_idx_o = 0; // facet barycenter block index
  31018. var block_idx_v1 = 0; // v1 vertex block index
  31019. var block_idx_v2 = 0; // v2 vertex block index
  31020. var block_idx_v3 = 0; // v3 vertex block index
  31021. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31022. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31023. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31024. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31025. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31026. subSq = options.subDiv.max * options.subDiv.max;
  31027. options.facetPartitioning.length = 0;
  31028. }
  31029. // reset the normals
  31030. for (index = 0; index < positions.length; index++) {
  31031. normals[index] = 0.0;
  31032. }
  31033. // Loop : 1 indice triplet = 1 facet
  31034. var nbFaces = (indices.length / 3) | 0;
  31035. for (index = 0; index < nbFaces; index++) {
  31036. // get the indexes of the coordinates of each vertex of the facet
  31037. v1x = indices[index * 3] * 3;
  31038. v1y = v1x + 1;
  31039. v1z = v1x + 2;
  31040. v2x = indices[index * 3 + 1] * 3;
  31041. v2y = v2x + 1;
  31042. v2z = v2x + 2;
  31043. v3x = indices[index * 3 + 2] * 3;
  31044. v3y = v3x + 1;
  31045. v3z = v3x + 2;
  31046. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31047. p1p2y = positions[v1y] - positions[v2y];
  31048. p1p2z = positions[v1z] - positions[v2z];
  31049. p3p2x = positions[v3x] - positions[v2x];
  31050. p3p2y = positions[v3y] - positions[v2y];
  31051. p3p2z = positions[v3z] - positions[v2z];
  31052. // compute the face normal with the cross product
  31053. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31054. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31055. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31056. // normalize this normal and store it in the array facetData
  31057. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31058. length = (length === 0) ? 1.0 : length;
  31059. faceNormalx /= length;
  31060. faceNormaly /= length;
  31061. faceNormalz /= length;
  31062. if (computeFacetNormals && options) {
  31063. options.facetNormals[index].x = faceNormalx;
  31064. options.facetNormals[index].y = faceNormaly;
  31065. options.facetNormals[index].z = faceNormalz;
  31066. }
  31067. if (computeFacetPositions && options) {
  31068. // compute and the facet barycenter coordinates in the array facetPositions
  31069. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31070. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31071. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31072. }
  31073. if (computeFacetPartitioning && options) {
  31074. // store the facet indexes in arrays in the main facetPartitioning array :
  31075. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31076. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31077. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31078. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31079. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31080. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31081. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31082. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31083. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31084. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31085. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31086. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31087. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31088. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31089. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31090. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31091. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31092. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31093. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31094. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31095. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31096. // push each facet index in each block containing the vertex
  31097. options.facetPartitioning[block_idx_v1].push(index);
  31098. if (block_idx_v2 != block_idx_v1) {
  31099. options.facetPartitioning[block_idx_v2].push(index);
  31100. }
  31101. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31102. options.facetPartitioning[block_idx_v3].push(index);
  31103. }
  31104. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31105. options.facetPartitioning[block_idx_o].push(index);
  31106. }
  31107. }
  31108. if (computeDepthSort && options && options.facetPositions) {
  31109. var dsf = depthSortedFacets[index];
  31110. dsf.ind = index * 3;
  31111. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31112. }
  31113. // compute the normals anyway
  31114. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31115. normals[v1y] += faceNormaly;
  31116. normals[v1z] += faceNormalz;
  31117. normals[v2x] += faceNormalx;
  31118. normals[v2y] += faceNormaly;
  31119. normals[v2z] += faceNormalz;
  31120. normals[v3x] += faceNormalx;
  31121. normals[v3y] += faceNormaly;
  31122. normals[v3z] += faceNormalz;
  31123. }
  31124. // last normalization of each normal
  31125. for (index = 0; index < normals.length / 3; index++) {
  31126. faceNormalx = normals[index * 3];
  31127. faceNormaly = normals[index * 3 + 1];
  31128. faceNormalz = normals[index * 3 + 2];
  31129. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31130. length = (length === 0) ? 1.0 : length;
  31131. faceNormalx /= length;
  31132. faceNormaly /= length;
  31133. faceNormalz /= length;
  31134. normals[index * 3] = faceNormalx;
  31135. normals[index * 3 + 1] = faceNormaly;
  31136. normals[index * 3 + 2] = faceNormalz;
  31137. }
  31138. };
  31139. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31140. var li = indices.length;
  31141. var ln = normals.length;
  31142. var i;
  31143. var n;
  31144. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31145. switch (sideOrientation) {
  31146. case BABYLON.Mesh.FRONTSIDE:
  31147. // nothing changed
  31148. break;
  31149. case BABYLON.Mesh.BACKSIDE:
  31150. var tmp;
  31151. // indices
  31152. for (i = 0; i < li; i += 3) {
  31153. tmp = indices[i];
  31154. indices[i] = indices[i + 2];
  31155. indices[i + 2] = tmp;
  31156. }
  31157. // normals
  31158. for (n = 0; n < ln; n++) {
  31159. normals[n] = -normals[n];
  31160. }
  31161. break;
  31162. case BABYLON.Mesh.DOUBLESIDE:
  31163. // positions
  31164. var lp = positions.length;
  31165. var l = lp / 3;
  31166. for (var p = 0; p < lp; p++) {
  31167. positions[lp + p] = positions[p];
  31168. }
  31169. // indices
  31170. for (i = 0; i < li; i += 3) {
  31171. indices[i + li] = indices[i + 2] + l;
  31172. indices[i + 1 + li] = indices[i + 1] + l;
  31173. indices[i + 2 + li] = indices[i] + l;
  31174. }
  31175. // normals
  31176. for (n = 0; n < ln; n++) {
  31177. normals[ln + n] = -normals[n];
  31178. }
  31179. // uvs
  31180. var lu = uvs.length;
  31181. var u = 0;
  31182. for (u = 0; u < lu; u++) {
  31183. uvs[u + lu] = uvs[u];
  31184. }
  31185. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31186. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31187. u = 0;
  31188. for (i = 0; i < lu / 2; i++) {
  31189. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31190. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31191. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31192. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31193. u += 2;
  31194. }
  31195. break;
  31196. }
  31197. };
  31198. /**
  31199. * Creates a new VertexData from the imported parameters.
  31200. */
  31201. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31202. var vertexData = new VertexData();
  31203. // positions
  31204. var positions = parsedVertexData.positions;
  31205. if (positions) {
  31206. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31207. }
  31208. // normals
  31209. var normals = parsedVertexData.normals;
  31210. if (normals) {
  31211. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31212. }
  31213. // tangents
  31214. var tangents = parsedVertexData.tangents;
  31215. if (tangents) {
  31216. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31217. }
  31218. // uvs
  31219. var uvs = parsedVertexData.uvs;
  31220. if (uvs) {
  31221. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31222. }
  31223. // uv2s
  31224. var uv2s = parsedVertexData.uv2s;
  31225. if (uv2s) {
  31226. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31227. }
  31228. // uv3s
  31229. var uv3s = parsedVertexData.uv3s;
  31230. if (uv3s) {
  31231. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31232. }
  31233. // uv4s
  31234. var uv4s = parsedVertexData.uv4s;
  31235. if (uv4s) {
  31236. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31237. }
  31238. // uv5s
  31239. var uv5s = parsedVertexData.uv5s;
  31240. if (uv5s) {
  31241. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31242. }
  31243. // uv6s
  31244. var uv6s = parsedVertexData.uv6s;
  31245. if (uv6s) {
  31246. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31247. }
  31248. // colors
  31249. var colors = parsedVertexData.colors;
  31250. if (colors) {
  31251. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31252. }
  31253. // matricesIndices
  31254. var matricesIndices = parsedVertexData.matricesIndices;
  31255. if (matricesIndices) {
  31256. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31257. }
  31258. // matricesWeights
  31259. var matricesWeights = parsedVertexData.matricesWeights;
  31260. if (matricesWeights) {
  31261. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31262. }
  31263. // indices
  31264. var indices = parsedVertexData.indices;
  31265. if (indices) {
  31266. vertexData.indices = indices;
  31267. }
  31268. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31269. };
  31270. return VertexData;
  31271. }());
  31272. BABYLON.VertexData = VertexData;
  31273. })(BABYLON || (BABYLON = {}));
  31274. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31275. var BABYLON;
  31276. (function (BABYLON) {
  31277. var Geometry = /** @class */ (function () {
  31278. function Geometry(id, scene, vertexData, updatable, mesh) {
  31279. if (updatable === void 0) { updatable = false; }
  31280. if (mesh === void 0) { mesh = null; }
  31281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31282. this._totalVertices = 0;
  31283. this._isDisposed = false;
  31284. this._indexBufferIsUpdatable = false;
  31285. this.id = id;
  31286. this._engine = scene.getEngine();
  31287. this._meshes = [];
  31288. this._scene = scene;
  31289. //Init vertex buffer cache
  31290. this._vertexBuffers = {};
  31291. this._indices = [];
  31292. this._updatable = updatable;
  31293. // vertexData
  31294. if (vertexData) {
  31295. this.setAllVerticesData(vertexData, updatable);
  31296. }
  31297. else {
  31298. this._totalVertices = 0;
  31299. this._indices = [];
  31300. }
  31301. if (this._engine.getCaps().vertexArrayObject) {
  31302. this._vertexArrayObjects = {};
  31303. }
  31304. // applyToMesh
  31305. if (mesh) {
  31306. if (mesh.getClassName() === "LinesMesh") {
  31307. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31308. this.updateExtend();
  31309. }
  31310. this.applyToMesh(mesh);
  31311. mesh.computeWorldMatrix(true);
  31312. }
  31313. }
  31314. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31315. /**
  31316. * 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
  31317. * @returns The Bias Vector
  31318. */
  31319. get: function () {
  31320. return this._boundingBias;
  31321. },
  31322. set: function (value) {
  31323. if (this._boundingBias && this._boundingBias.equals(value)) {
  31324. return;
  31325. }
  31326. this._boundingBias = value.clone();
  31327. this.updateBoundingInfo(true, null);
  31328. },
  31329. enumerable: true,
  31330. configurable: true
  31331. });
  31332. Geometry.CreateGeometryForMesh = function (mesh) {
  31333. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31334. geometry.applyToMesh(mesh);
  31335. return geometry;
  31336. };
  31337. Object.defineProperty(Geometry.prototype, "extend", {
  31338. get: function () {
  31339. return this._extend;
  31340. },
  31341. enumerable: true,
  31342. configurable: true
  31343. });
  31344. Geometry.prototype.getScene = function () {
  31345. return this._scene;
  31346. };
  31347. Geometry.prototype.getEngine = function () {
  31348. return this._engine;
  31349. };
  31350. Geometry.prototype.isReady = function () {
  31351. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31352. };
  31353. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31354. get: function () {
  31355. for (var index = 0; index < this._meshes.length; index++) {
  31356. if (!this._meshes[index].doNotSerialize) {
  31357. return false;
  31358. }
  31359. }
  31360. return true;
  31361. },
  31362. enumerable: true,
  31363. configurable: true
  31364. });
  31365. Geometry.prototype._rebuild = function () {
  31366. if (this._vertexArrayObjects) {
  31367. this._vertexArrayObjects = {};
  31368. }
  31369. // Index buffer
  31370. if (this._meshes.length !== 0 && this._indices) {
  31371. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31372. }
  31373. // Vertex buffers
  31374. for (var key in this._vertexBuffers) {
  31375. var vertexBuffer = this._vertexBuffers[key];
  31376. vertexBuffer._rebuild();
  31377. }
  31378. };
  31379. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31380. vertexData.applyToGeometry(this, updatable);
  31381. this.notifyUpdate();
  31382. };
  31383. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31384. if (updatable === void 0) { updatable = false; }
  31385. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31386. this.setVerticesBuffer(buffer);
  31387. };
  31388. Geometry.prototype.removeVerticesData = function (kind) {
  31389. if (this._vertexBuffers[kind]) {
  31390. this._vertexBuffers[kind].dispose();
  31391. delete this._vertexBuffers[kind];
  31392. }
  31393. };
  31394. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31395. var kind = buffer.getKind();
  31396. if (this._vertexBuffers[kind]) {
  31397. this._vertexBuffers[kind].dispose();
  31398. }
  31399. this._vertexBuffers[kind] = buffer;
  31400. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31401. var data = buffer.getData();
  31402. var stride = buffer.getStrideSize();
  31403. this._totalVertices = data.length / stride;
  31404. this.updateExtend(data, stride);
  31405. this._resetPointsArrayCache();
  31406. var meshes = this._meshes;
  31407. var numOfMeshes = meshes.length;
  31408. for (var index = 0; index < numOfMeshes; index++) {
  31409. var mesh = meshes[index];
  31410. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31411. mesh._createGlobalSubMesh(false);
  31412. mesh.computeWorldMatrix(true);
  31413. }
  31414. }
  31415. this.notifyUpdate(kind);
  31416. if (this._vertexArrayObjects) {
  31417. this._disposeVertexArrayObjects();
  31418. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31419. }
  31420. };
  31421. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31422. var vertexBuffer = this.getVertexBuffer(kind);
  31423. if (!vertexBuffer) {
  31424. return;
  31425. }
  31426. vertexBuffer.updateDirectly(data, offset);
  31427. this.notifyUpdate(kind);
  31428. };
  31429. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31430. if (updateExtends === void 0) { updateExtends = false; }
  31431. var vertexBuffer = this.getVertexBuffer(kind);
  31432. if (!vertexBuffer) {
  31433. return;
  31434. }
  31435. vertexBuffer.update(data);
  31436. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31437. var stride = vertexBuffer.getStrideSize();
  31438. this._totalVertices = data.length / stride;
  31439. this.updateBoundingInfo(updateExtends, data);
  31440. }
  31441. this.notifyUpdate(kind);
  31442. };
  31443. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31444. if (updateExtends) {
  31445. this.updateExtend(data);
  31446. }
  31447. var meshes = this._meshes;
  31448. var numOfMeshes = meshes.length;
  31449. this._resetPointsArrayCache();
  31450. for (var index = 0; index < numOfMeshes; index++) {
  31451. var mesh = meshes[index];
  31452. if (updateExtends) {
  31453. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31454. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31455. var subMesh = mesh.subMeshes[subIndex];
  31456. subMesh.refreshBoundingInfo();
  31457. }
  31458. }
  31459. }
  31460. };
  31461. Geometry.prototype._bind = function (effect, indexToBind) {
  31462. if (!effect) {
  31463. return;
  31464. }
  31465. if (indexToBind === undefined) {
  31466. indexToBind = this._indexBuffer;
  31467. }
  31468. var vbs = this.getVertexBuffers();
  31469. if (!vbs) {
  31470. return;
  31471. }
  31472. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31473. this._engine.bindBuffers(vbs, indexToBind, effect);
  31474. return;
  31475. }
  31476. // Using VAO
  31477. if (!this._vertexArrayObjects[effect.key]) {
  31478. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31479. }
  31480. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31481. };
  31482. Geometry.prototype.getTotalVertices = function () {
  31483. if (!this.isReady()) {
  31484. return 0;
  31485. }
  31486. return this._totalVertices;
  31487. };
  31488. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31489. var vertexBuffer = this.getVertexBuffer(kind);
  31490. if (!vertexBuffer) {
  31491. return null;
  31492. }
  31493. var orig = vertexBuffer.getData();
  31494. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31495. return orig;
  31496. }
  31497. else {
  31498. var len = orig.length;
  31499. var copy = [];
  31500. for (var i = 0; i < len; i++) {
  31501. copy.push(orig[i]);
  31502. }
  31503. return copy;
  31504. }
  31505. };
  31506. /**
  31507. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31508. * Possible `kind` values :
  31509. * - BABYLON.VertexBuffer.PositionKind
  31510. * - BABYLON.VertexBuffer.UVKind
  31511. * - BABYLON.VertexBuffer.UV2Kind
  31512. * - BABYLON.VertexBuffer.UV3Kind
  31513. * - BABYLON.VertexBuffer.UV4Kind
  31514. * - BABYLON.VertexBuffer.UV5Kind
  31515. * - BABYLON.VertexBuffer.UV6Kind
  31516. * - BABYLON.VertexBuffer.ColorKind
  31517. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31518. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31519. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31520. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31521. */
  31522. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31523. var vb = this._vertexBuffers[kind];
  31524. if (!vb) {
  31525. return false;
  31526. }
  31527. return vb.isUpdatable();
  31528. };
  31529. Geometry.prototype.getVertexBuffer = function (kind) {
  31530. if (!this.isReady()) {
  31531. return null;
  31532. }
  31533. return this._vertexBuffers[kind];
  31534. };
  31535. Geometry.prototype.getVertexBuffers = function () {
  31536. if (!this.isReady()) {
  31537. return null;
  31538. }
  31539. return this._vertexBuffers;
  31540. };
  31541. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31542. if (!this._vertexBuffers) {
  31543. if (this._delayInfo) {
  31544. return this._delayInfo.indexOf(kind) !== -1;
  31545. }
  31546. return false;
  31547. }
  31548. return this._vertexBuffers[kind] !== undefined;
  31549. };
  31550. Geometry.prototype.getVerticesDataKinds = function () {
  31551. var result = [];
  31552. var kind;
  31553. if (!this._vertexBuffers && this._delayInfo) {
  31554. for (kind in this._delayInfo) {
  31555. result.push(kind);
  31556. }
  31557. }
  31558. else {
  31559. for (kind in this._vertexBuffers) {
  31560. result.push(kind);
  31561. }
  31562. }
  31563. return result;
  31564. };
  31565. Geometry.prototype.updateIndices = function (indices, offset) {
  31566. if (!this._indexBuffer) {
  31567. return;
  31568. }
  31569. if (!this._indexBufferIsUpdatable) {
  31570. this.setIndices(indices, null, true);
  31571. }
  31572. else {
  31573. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31574. }
  31575. };
  31576. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31577. if (totalVertices === void 0) { totalVertices = null; }
  31578. if (updatable === void 0) { updatable = false; }
  31579. if (this._indexBuffer) {
  31580. this._engine._releaseBuffer(this._indexBuffer);
  31581. }
  31582. this._disposeVertexArrayObjects();
  31583. this._indices = indices;
  31584. this._indexBufferIsUpdatable = updatable;
  31585. if (this._meshes.length !== 0 && this._indices) {
  31586. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31587. }
  31588. if (totalVertices != undefined) {
  31589. this._totalVertices = totalVertices;
  31590. }
  31591. var meshes = this._meshes;
  31592. var numOfMeshes = meshes.length;
  31593. for (var index = 0; index < numOfMeshes; index++) {
  31594. meshes[index]._createGlobalSubMesh(true);
  31595. }
  31596. this.notifyUpdate();
  31597. };
  31598. Geometry.prototype.getTotalIndices = function () {
  31599. if (!this.isReady()) {
  31600. return 0;
  31601. }
  31602. return this._indices.length;
  31603. };
  31604. Geometry.prototype.getIndices = function (copyWhenShared) {
  31605. if (!this.isReady()) {
  31606. return null;
  31607. }
  31608. var orig = this._indices;
  31609. if (!copyWhenShared || this._meshes.length === 1) {
  31610. return orig;
  31611. }
  31612. else {
  31613. var len = orig.length;
  31614. var copy = [];
  31615. for (var i = 0; i < len; i++) {
  31616. copy.push(orig[i]);
  31617. }
  31618. return copy;
  31619. }
  31620. };
  31621. Geometry.prototype.getIndexBuffer = function () {
  31622. if (!this.isReady()) {
  31623. return null;
  31624. }
  31625. return this._indexBuffer;
  31626. };
  31627. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31628. if (effect === void 0) { effect = null; }
  31629. if (!effect || !this._vertexArrayObjects) {
  31630. return;
  31631. }
  31632. if (this._vertexArrayObjects[effect.key]) {
  31633. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31634. delete this._vertexArrayObjects[effect.key];
  31635. }
  31636. };
  31637. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31638. var meshes = this._meshes;
  31639. var index = meshes.indexOf(mesh);
  31640. if (index === -1) {
  31641. return;
  31642. }
  31643. meshes.splice(index, 1);
  31644. mesh._geometry = null;
  31645. if (meshes.length === 0 && shouldDispose) {
  31646. this.dispose();
  31647. }
  31648. };
  31649. Geometry.prototype.applyToMesh = function (mesh) {
  31650. if (mesh._geometry === this) {
  31651. return;
  31652. }
  31653. var previousGeometry = mesh._geometry;
  31654. if (previousGeometry) {
  31655. previousGeometry.releaseForMesh(mesh);
  31656. }
  31657. var meshes = this._meshes;
  31658. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31659. mesh._geometry = this;
  31660. this._scene.pushGeometry(this);
  31661. meshes.push(mesh);
  31662. if (this.isReady()) {
  31663. this._applyToMesh(mesh);
  31664. }
  31665. else {
  31666. mesh._boundingInfo = this._boundingInfo;
  31667. }
  31668. };
  31669. Geometry.prototype.updateExtend = function (data, stride) {
  31670. if (data === void 0) { data = null; }
  31671. if (!data) {
  31672. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31673. }
  31674. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31675. };
  31676. Geometry.prototype._applyToMesh = function (mesh) {
  31677. var numOfMeshes = this._meshes.length;
  31678. // vertexBuffers
  31679. for (var kind in this._vertexBuffers) {
  31680. if (numOfMeshes === 1) {
  31681. this._vertexBuffers[kind].create();
  31682. }
  31683. var buffer = this._vertexBuffers[kind].getBuffer();
  31684. if (buffer)
  31685. buffer.references = numOfMeshes;
  31686. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31687. if (!this._extend) {
  31688. this.updateExtend(this._vertexBuffers[kind].getData());
  31689. }
  31690. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31691. mesh._createGlobalSubMesh(false);
  31692. //bounding info was just created again, world matrix should be applied again.
  31693. mesh._updateBoundingInfo();
  31694. }
  31695. }
  31696. // indexBuffer
  31697. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31698. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31699. }
  31700. if (this._indexBuffer) {
  31701. this._indexBuffer.references = numOfMeshes;
  31702. }
  31703. };
  31704. Geometry.prototype.notifyUpdate = function (kind) {
  31705. if (this.onGeometryUpdated) {
  31706. this.onGeometryUpdated(this, kind);
  31707. }
  31708. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31709. var mesh = _a[_i];
  31710. mesh._markSubMeshesAsAttributesDirty();
  31711. }
  31712. };
  31713. Geometry.prototype.load = function (scene, onLoaded) {
  31714. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31715. return;
  31716. }
  31717. if (this.isReady()) {
  31718. if (onLoaded) {
  31719. onLoaded();
  31720. }
  31721. return;
  31722. }
  31723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31724. this._queueLoad(scene, onLoaded);
  31725. };
  31726. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31727. var _this = this;
  31728. if (!this.delayLoadingFile) {
  31729. return;
  31730. }
  31731. scene._addPendingData(this);
  31732. scene._loadFile(this.delayLoadingFile, function (data) {
  31733. if (!_this._delayLoadingFunction) {
  31734. return;
  31735. }
  31736. _this._delayLoadingFunction(JSON.parse(data), _this);
  31737. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31738. _this._delayInfo = [];
  31739. scene._removePendingData(_this);
  31740. var meshes = _this._meshes;
  31741. var numOfMeshes = meshes.length;
  31742. for (var index = 0; index < numOfMeshes; index++) {
  31743. _this._applyToMesh(meshes[index]);
  31744. }
  31745. if (onLoaded) {
  31746. onLoaded();
  31747. }
  31748. }, undefined, true);
  31749. };
  31750. /**
  31751. * Invert the geometry to move from a right handed system to a left handed one.
  31752. */
  31753. Geometry.prototype.toLeftHanded = function () {
  31754. // Flip faces
  31755. var tIndices = this.getIndices(false);
  31756. if (tIndices != null && tIndices.length > 0) {
  31757. for (var i = 0; i < tIndices.length; i += 3) {
  31758. var tTemp = tIndices[i + 0];
  31759. tIndices[i + 0] = tIndices[i + 2];
  31760. tIndices[i + 2] = tTemp;
  31761. }
  31762. this.setIndices(tIndices);
  31763. }
  31764. // Negate position.z
  31765. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31766. if (tPositions != null && tPositions.length > 0) {
  31767. for (var i = 0; i < tPositions.length; i += 3) {
  31768. tPositions[i + 2] = -tPositions[i + 2];
  31769. }
  31770. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31771. }
  31772. // Negate normal.z
  31773. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31774. if (tNormals != null && tNormals.length > 0) {
  31775. for (var i = 0; i < tNormals.length; i += 3) {
  31776. tNormals[i + 2] = -tNormals[i + 2];
  31777. }
  31778. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31779. }
  31780. };
  31781. // Cache
  31782. Geometry.prototype._resetPointsArrayCache = function () {
  31783. this._positions = null;
  31784. };
  31785. Geometry.prototype._generatePointsArray = function () {
  31786. if (this._positions)
  31787. return true;
  31788. this._positions = [];
  31789. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31790. if (!data) {
  31791. return false;
  31792. }
  31793. for (var index = 0; index < data.length; index += 3) {
  31794. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31795. }
  31796. return true;
  31797. };
  31798. Geometry.prototype.isDisposed = function () {
  31799. return this._isDisposed;
  31800. };
  31801. Geometry.prototype._disposeVertexArrayObjects = function () {
  31802. if (this._vertexArrayObjects) {
  31803. for (var kind in this._vertexArrayObjects) {
  31804. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31805. }
  31806. this._vertexArrayObjects = {};
  31807. }
  31808. };
  31809. Geometry.prototype.dispose = function () {
  31810. var meshes = this._meshes;
  31811. var numOfMeshes = meshes.length;
  31812. var index;
  31813. for (index = 0; index < numOfMeshes; index++) {
  31814. this.releaseForMesh(meshes[index]);
  31815. }
  31816. this._meshes = [];
  31817. this._disposeVertexArrayObjects();
  31818. for (var kind in this._vertexBuffers) {
  31819. this._vertexBuffers[kind].dispose();
  31820. }
  31821. this._vertexBuffers = {};
  31822. this._totalVertices = 0;
  31823. if (this._indexBuffer) {
  31824. this._engine._releaseBuffer(this._indexBuffer);
  31825. }
  31826. this._indexBuffer = null;
  31827. this._indices = [];
  31828. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31829. this.delayLoadingFile = null;
  31830. this._delayLoadingFunction = null;
  31831. this._delayInfo = [];
  31832. this._boundingInfo = null;
  31833. this._scene.removeGeometry(this);
  31834. this._isDisposed = true;
  31835. };
  31836. Geometry.prototype.copy = function (id) {
  31837. var vertexData = new BABYLON.VertexData();
  31838. vertexData.indices = [];
  31839. var indices = this.getIndices();
  31840. if (indices) {
  31841. for (var index = 0; index < indices.length; index++) {
  31842. vertexData.indices.push(indices[index]);
  31843. }
  31844. }
  31845. var updatable = false;
  31846. var stopChecking = false;
  31847. var kind;
  31848. for (kind in this._vertexBuffers) {
  31849. // using slice() to make a copy of the array and not just reference it
  31850. var data = this.getVerticesData(kind);
  31851. if (data instanceof Float32Array) {
  31852. vertexData.set(new Float32Array(data), kind);
  31853. }
  31854. else {
  31855. vertexData.set(data.slice(0), kind);
  31856. }
  31857. if (!stopChecking) {
  31858. var vb = this.getVertexBuffer(kind);
  31859. if (vb) {
  31860. updatable = vb.isUpdatable();
  31861. stopChecking = !updatable;
  31862. }
  31863. }
  31864. }
  31865. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31866. geometry.delayLoadState = this.delayLoadState;
  31867. geometry.delayLoadingFile = this.delayLoadingFile;
  31868. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31869. for (kind in this._delayInfo) {
  31870. geometry._delayInfo = geometry._delayInfo || [];
  31871. geometry._delayInfo.push(kind);
  31872. }
  31873. // Bounding info
  31874. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31875. return geometry;
  31876. };
  31877. Geometry.prototype.serialize = function () {
  31878. var serializationObject = {};
  31879. serializationObject.id = this.id;
  31880. serializationObject.updatable = this._updatable;
  31881. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31882. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31883. }
  31884. return serializationObject;
  31885. };
  31886. Geometry.prototype.toNumberArray = function (origin) {
  31887. if (Array.isArray(origin)) {
  31888. return origin;
  31889. }
  31890. else {
  31891. return Array.prototype.slice.call(origin);
  31892. }
  31893. };
  31894. Geometry.prototype.serializeVerticeData = function () {
  31895. var serializationObject = this.serialize();
  31896. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31897. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31898. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31899. serializationObject.positions._updatable = true;
  31900. }
  31901. }
  31902. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31903. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31904. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31905. serializationObject.normals._updatable = true;
  31906. }
  31907. }
  31908. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31909. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31910. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31911. serializationObject.uvs._updatable = true;
  31912. }
  31913. }
  31914. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31915. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31916. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31917. serializationObject.uv2s._updatable = true;
  31918. }
  31919. }
  31920. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31921. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31922. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31923. serializationObject.uv3s._updatable = true;
  31924. }
  31925. }
  31926. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31927. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31928. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31929. serializationObject.uv4s._updatable = true;
  31930. }
  31931. }
  31932. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31933. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31934. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31935. serializationObject.uv5s._updatable = true;
  31936. }
  31937. }
  31938. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31939. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31940. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31941. serializationObject.uv6s._updatable = true;
  31942. }
  31943. }
  31944. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31945. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31946. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31947. serializationObject.colors._updatable = true;
  31948. }
  31949. }
  31950. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31951. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31952. serializationObject.matricesIndices._isExpanded = true;
  31953. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31954. serializationObject.matricesIndices._updatable = true;
  31955. }
  31956. }
  31957. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31958. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31959. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31960. serializationObject.matricesWeights._updatable = true;
  31961. }
  31962. }
  31963. serializationObject.indices = this.toNumberArray(this.getIndices());
  31964. return serializationObject;
  31965. };
  31966. // Statics
  31967. Geometry.ExtractFromMesh = function (mesh, id) {
  31968. var geometry = mesh._geometry;
  31969. if (!geometry) {
  31970. return null;
  31971. }
  31972. return geometry.copy(id);
  31973. };
  31974. /**
  31975. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31976. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31977. * Be aware Math.random() could cause collisions, but:
  31978. * "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"
  31979. */
  31980. Geometry.RandomId = function () {
  31981. return BABYLON.Tools.RandomId();
  31982. };
  31983. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31984. var scene = mesh.getScene();
  31985. // Geometry
  31986. var geometryId = parsedGeometry.geometryId;
  31987. if (geometryId) {
  31988. var geometry = scene.getGeometryByID(geometryId);
  31989. if (geometry) {
  31990. geometry.applyToMesh(mesh);
  31991. }
  31992. }
  31993. else if (parsedGeometry instanceof ArrayBuffer) {
  31994. var binaryInfo = mesh._binaryInfo;
  31995. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31996. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31997. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31998. }
  31999. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32000. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32001. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32002. }
  32003. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32004. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32005. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32006. }
  32007. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32008. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32009. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32010. }
  32011. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32012. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32013. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32014. }
  32015. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32016. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32017. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32018. }
  32019. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32020. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32021. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32022. }
  32023. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32024. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32025. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32026. }
  32027. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32028. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32029. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32030. }
  32031. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32032. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32033. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32034. }
  32035. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32036. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32037. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32038. }
  32039. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32040. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32041. mesh.setIndices(indicesData, null);
  32042. }
  32043. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32044. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32045. mesh.subMeshes = [];
  32046. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32047. var materialIndex = subMeshesData[(i * 5) + 0];
  32048. var verticesStart = subMeshesData[(i * 5) + 1];
  32049. var verticesCount = subMeshesData[(i * 5) + 2];
  32050. var indexStart = subMeshesData[(i * 5) + 3];
  32051. var indexCount = subMeshesData[(i * 5) + 4];
  32052. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32053. }
  32054. }
  32055. }
  32056. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32057. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32058. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32059. if (parsedGeometry.uvs) {
  32060. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32061. }
  32062. if (parsedGeometry.uvs2) {
  32063. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32064. }
  32065. if (parsedGeometry.uvs3) {
  32066. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32067. }
  32068. if (parsedGeometry.uvs4) {
  32069. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32070. }
  32071. if (parsedGeometry.uvs5) {
  32072. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32073. }
  32074. if (parsedGeometry.uvs6) {
  32075. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32076. }
  32077. if (parsedGeometry.colors) {
  32078. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32079. }
  32080. if (parsedGeometry.matricesIndices) {
  32081. if (!parsedGeometry.matricesIndices._isExpanded) {
  32082. var floatIndices = [];
  32083. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32084. var matricesIndex = parsedGeometry.matricesIndices[i];
  32085. floatIndices.push(matricesIndex & 0x000000FF);
  32086. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32087. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32088. floatIndices.push(matricesIndex >> 24);
  32089. }
  32090. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32091. }
  32092. else {
  32093. delete parsedGeometry.matricesIndices._isExpanded;
  32094. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32095. }
  32096. }
  32097. if (parsedGeometry.matricesIndicesExtra) {
  32098. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32099. var floatIndices = [];
  32100. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32101. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32102. floatIndices.push(matricesIndex & 0x000000FF);
  32103. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32104. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32105. floatIndices.push(matricesIndex >> 24);
  32106. }
  32107. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32108. }
  32109. else {
  32110. delete parsedGeometry.matricesIndices._isExpanded;
  32111. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32112. }
  32113. }
  32114. if (parsedGeometry.matricesWeights) {
  32115. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32117. }
  32118. if (parsedGeometry.matricesWeightsExtra) {
  32119. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32120. }
  32121. mesh.setIndices(parsedGeometry.indices, null);
  32122. }
  32123. // SubMeshes
  32124. if (parsedGeometry.subMeshes) {
  32125. mesh.subMeshes = [];
  32126. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32127. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32128. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32129. }
  32130. }
  32131. // Flat shading
  32132. if (mesh._shouldGenerateFlatShading) {
  32133. mesh.convertToFlatShadedMesh();
  32134. delete mesh._shouldGenerateFlatShading;
  32135. }
  32136. // Update
  32137. mesh.computeWorldMatrix(true);
  32138. // Octree
  32139. var sceneOctree = scene.selectionOctree;
  32140. if (sceneOctree !== undefined && sceneOctree !== null) {
  32141. sceneOctree.addMesh(mesh);
  32142. }
  32143. };
  32144. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32145. var epsilon = 1e-3;
  32146. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32147. return;
  32148. }
  32149. var noInfluenceBoneIndex = 0.0;
  32150. if (parsedGeometry.skeletonId > -1) {
  32151. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32152. if (!skeleton) {
  32153. return;
  32154. }
  32155. noInfluenceBoneIndex = skeleton.bones.length;
  32156. }
  32157. else {
  32158. return;
  32159. }
  32160. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32161. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32162. var matricesWeights = parsedGeometry.matricesWeights;
  32163. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32164. var influencers = parsedGeometry.numBoneInfluencer;
  32165. var size = matricesWeights.length;
  32166. for (var i = 0; i < size; i += 4) {
  32167. var weight = 0.0;
  32168. var firstZeroWeight = -1;
  32169. for (var j = 0; j < 4; j++) {
  32170. var w = matricesWeights[i + j];
  32171. weight += w;
  32172. if (w < epsilon && firstZeroWeight < 0) {
  32173. firstZeroWeight = j;
  32174. }
  32175. }
  32176. if (matricesWeightsExtra) {
  32177. for (var j = 0; j < 4; j++) {
  32178. var w = matricesWeightsExtra[i + j];
  32179. weight += w;
  32180. if (w < epsilon && firstZeroWeight < 0) {
  32181. firstZeroWeight = j + 4;
  32182. }
  32183. }
  32184. }
  32185. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32186. firstZeroWeight = influencers - 1;
  32187. }
  32188. if (weight > epsilon) {
  32189. var mweight = 1.0 / weight;
  32190. for (var j = 0; j < 4; j++) {
  32191. matricesWeights[i + j] *= mweight;
  32192. }
  32193. if (matricesWeightsExtra) {
  32194. for (var j = 0; j < 4; j++) {
  32195. matricesWeightsExtra[i + j] *= mweight;
  32196. }
  32197. }
  32198. }
  32199. else {
  32200. if (firstZeroWeight >= 4) {
  32201. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32202. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32203. }
  32204. else {
  32205. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32206. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32207. }
  32208. }
  32209. }
  32210. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32211. if (parsedGeometry.matricesWeightsExtra) {
  32212. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32213. }
  32214. };
  32215. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32216. if (scene.getGeometryByID(parsedVertexData.id)) {
  32217. return null; // null since geometry could be something else than a box...
  32218. }
  32219. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32220. if (BABYLON.Tags) {
  32221. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32222. }
  32223. if (parsedVertexData.delayLoadingFile) {
  32224. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32225. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32226. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32227. geometry._delayInfo = [];
  32228. if (parsedVertexData.hasUVs) {
  32229. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32230. }
  32231. if (parsedVertexData.hasUVs2) {
  32232. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32233. }
  32234. if (parsedVertexData.hasUVs3) {
  32235. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32236. }
  32237. if (parsedVertexData.hasUVs4) {
  32238. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32239. }
  32240. if (parsedVertexData.hasUVs5) {
  32241. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32242. }
  32243. if (parsedVertexData.hasUVs6) {
  32244. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32245. }
  32246. if (parsedVertexData.hasColors) {
  32247. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32248. }
  32249. if (parsedVertexData.hasMatricesIndices) {
  32250. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32251. }
  32252. if (parsedVertexData.hasMatricesWeights) {
  32253. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32254. }
  32255. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32256. }
  32257. else {
  32258. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32259. }
  32260. scene.pushGeometry(geometry, true);
  32261. return geometry;
  32262. };
  32263. return Geometry;
  32264. }());
  32265. BABYLON.Geometry = Geometry;
  32266. /////// Primitives //////////////////////////////////////////////
  32267. //export module Geometry.Primitives {
  32268. /// Abstract class
  32269. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32270. __extends(_PrimitiveGeometry, _super);
  32271. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32272. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32273. if (mesh === void 0) { mesh = null; }
  32274. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32275. _this._canBeRegenerated = _canBeRegenerated;
  32276. _this._beingRegenerated = true;
  32277. _this.regenerate();
  32278. _this._beingRegenerated = false;
  32279. return _this;
  32280. }
  32281. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32282. return this._canBeRegenerated;
  32283. };
  32284. _PrimitiveGeometry.prototype.regenerate = function () {
  32285. if (!this._canBeRegenerated) {
  32286. return;
  32287. }
  32288. this._beingRegenerated = true;
  32289. this.setAllVerticesData(this._regenerateVertexData(), false);
  32290. this._beingRegenerated = false;
  32291. };
  32292. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32293. return _super.prototype.copy.call(this, id);
  32294. };
  32295. // overrides
  32296. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32297. if (!this._beingRegenerated) {
  32298. return;
  32299. }
  32300. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32301. };
  32302. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32303. if (!this._beingRegenerated) {
  32304. return;
  32305. }
  32306. _super.prototype.setVerticesData.call(this, kind, data, false);
  32307. };
  32308. // to override
  32309. // protected
  32310. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32311. throw new Error("Abstract method");
  32312. };
  32313. _PrimitiveGeometry.prototype.copy = function (id) {
  32314. throw new Error("Must be overriden in sub-classes.");
  32315. };
  32316. _PrimitiveGeometry.prototype.serialize = function () {
  32317. var serializationObject = _super.prototype.serialize.call(this);
  32318. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32319. return serializationObject;
  32320. };
  32321. return _PrimitiveGeometry;
  32322. }(Geometry));
  32323. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32324. var RibbonGeometry = /** @class */ (function (_super) {
  32325. __extends(RibbonGeometry, _super);
  32326. // Members
  32327. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32328. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32329. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32330. _this.pathArray = pathArray;
  32331. _this.closeArray = closeArray;
  32332. _this.closePath = closePath;
  32333. _this.offset = offset;
  32334. _this.side = side;
  32335. return _this;
  32336. }
  32337. RibbonGeometry.prototype._regenerateVertexData = function () {
  32338. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32339. };
  32340. RibbonGeometry.prototype.copy = function (id) {
  32341. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32342. };
  32343. return RibbonGeometry;
  32344. }(_PrimitiveGeometry));
  32345. BABYLON.RibbonGeometry = RibbonGeometry;
  32346. var BoxGeometry = /** @class */ (function (_super) {
  32347. __extends(BoxGeometry, _super);
  32348. // Members
  32349. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32350. if (mesh === void 0) { mesh = null; }
  32351. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32352. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32353. _this.size = size;
  32354. _this.side = side;
  32355. return _this;
  32356. }
  32357. BoxGeometry.prototype._regenerateVertexData = function () {
  32358. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32359. };
  32360. BoxGeometry.prototype.copy = function (id) {
  32361. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32362. };
  32363. BoxGeometry.prototype.serialize = function () {
  32364. var serializationObject = _super.prototype.serialize.call(this);
  32365. serializationObject.size = this.size;
  32366. return serializationObject;
  32367. };
  32368. BoxGeometry.Parse = function (parsedBox, scene) {
  32369. if (scene.getGeometryByID(parsedBox.id)) {
  32370. return null; // null since geometry could be something else than a box...
  32371. }
  32372. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32373. if (BABYLON.Tags) {
  32374. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32375. }
  32376. scene.pushGeometry(box, true);
  32377. return box;
  32378. };
  32379. return BoxGeometry;
  32380. }(_PrimitiveGeometry));
  32381. BABYLON.BoxGeometry = BoxGeometry;
  32382. var SphereGeometry = /** @class */ (function (_super) {
  32383. __extends(SphereGeometry, _super);
  32384. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32385. if (mesh === void 0) { mesh = null; }
  32386. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32387. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32388. _this.segments = segments;
  32389. _this.diameter = diameter;
  32390. _this.side = side;
  32391. return _this;
  32392. }
  32393. SphereGeometry.prototype._regenerateVertexData = function () {
  32394. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32395. };
  32396. SphereGeometry.prototype.copy = function (id) {
  32397. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32398. };
  32399. SphereGeometry.prototype.serialize = function () {
  32400. var serializationObject = _super.prototype.serialize.call(this);
  32401. serializationObject.segments = this.segments;
  32402. serializationObject.diameter = this.diameter;
  32403. return serializationObject;
  32404. };
  32405. SphereGeometry.Parse = function (parsedSphere, scene) {
  32406. if (scene.getGeometryByID(parsedSphere.id)) {
  32407. return null; // null since geometry could be something else than a sphere...
  32408. }
  32409. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32410. if (BABYLON.Tags) {
  32411. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32412. }
  32413. scene.pushGeometry(sphere, true);
  32414. return sphere;
  32415. };
  32416. return SphereGeometry;
  32417. }(_PrimitiveGeometry));
  32418. BABYLON.SphereGeometry = SphereGeometry;
  32419. var DiscGeometry = /** @class */ (function (_super) {
  32420. __extends(DiscGeometry, _super);
  32421. // Members
  32422. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32423. if (mesh === void 0) { mesh = null; }
  32424. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32425. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32426. _this.radius = radius;
  32427. _this.tessellation = tessellation;
  32428. _this.side = side;
  32429. return _this;
  32430. }
  32431. DiscGeometry.prototype._regenerateVertexData = function () {
  32432. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32433. };
  32434. DiscGeometry.prototype.copy = function (id) {
  32435. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32436. };
  32437. return DiscGeometry;
  32438. }(_PrimitiveGeometry));
  32439. BABYLON.DiscGeometry = DiscGeometry;
  32440. var CylinderGeometry = /** @class */ (function (_super) {
  32441. __extends(CylinderGeometry, _super);
  32442. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32443. if (subdivisions === void 0) { subdivisions = 1; }
  32444. if (mesh === void 0) { mesh = null; }
  32445. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32446. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32447. _this.height = height;
  32448. _this.diameterTop = diameterTop;
  32449. _this.diameterBottom = diameterBottom;
  32450. _this.tessellation = tessellation;
  32451. _this.subdivisions = subdivisions;
  32452. _this.side = side;
  32453. return _this;
  32454. }
  32455. CylinderGeometry.prototype._regenerateVertexData = function () {
  32456. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32457. };
  32458. CylinderGeometry.prototype.copy = function (id) {
  32459. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32460. };
  32461. CylinderGeometry.prototype.serialize = function () {
  32462. var serializationObject = _super.prototype.serialize.call(this);
  32463. serializationObject.height = this.height;
  32464. serializationObject.diameterTop = this.diameterTop;
  32465. serializationObject.diameterBottom = this.diameterBottom;
  32466. serializationObject.tessellation = this.tessellation;
  32467. return serializationObject;
  32468. };
  32469. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32470. if (scene.getGeometryByID(parsedCylinder.id)) {
  32471. return null; // null since geometry could be something else than a cylinder...
  32472. }
  32473. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32474. if (BABYLON.Tags) {
  32475. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32476. }
  32477. scene.pushGeometry(cylinder, true);
  32478. return cylinder;
  32479. };
  32480. return CylinderGeometry;
  32481. }(_PrimitiveGeometry));
  32482. BABYLON.CylinderGeometry = CylinderGeometry;
  32483. var TorusGeometry = /** @class */ (function (_super) {
  32484. __extends(TorusGeometry, _super);
  32485. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32486. if (mesh === void 0) { mesh = null; }
  32487. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32488. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32489. _this.diameter = diameter;
  32490. _this.thickness = thickness;
  32491. _this.tessellation = tessellation;
  32492. _this.side = side;
  32493. return _this;
  32494. }
  32495. TorusGeometry.prototype._regenerateVertexData = function () {
  32496. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32497. };
  32498. TorusGeometry.prototype.copy = function (id) {
  32499. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32500. };
  32501. TorusGeometry.prototype.serialize = function () {
  32502. var serializationObject = _super.prototype.serialize.call(this);
  32503. serializationObject.diameter = this.diameter;
  32504. serializationObject.thickness = this.thickness;
  32505. serializationObject.tessellation = this.tessellation;
  32506. return serializationObject;
  32507. };
  32508. TorusGeometry.Parse = function (parsedTorus, scene) {
  32509. if (scene.getGeometryByID(parsedTorus.id)) {
  32510. return null; // null since geometry could be something else than a torus...
  32511. }
  32512. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32513. if (BABYLON.Tags) {
  32514. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32515. }
  32516. scene.pushGeometry(torus, true);
  32517. return torus;
  32518. };
  32519. return TorusGeometry;
  32520. }(_PrimitiveGeometry));
  32521. BABYLON.TorusGeometry = TorusGeometry;
  32522. var GroundGeometry = /** @class */ (function (_super) {
  32523. __extends(GroundGeometry, _super);
  32524. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32525. if (mesh === void 0) { mesh = null; }
  32526. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32527. _this.width = width;
  32528. _this.height = height;
  32529. _this.subdivisions = subdivisions;
  32530. return _this;
  32531. }
  32532. GroundGeometry.prototype._regenerateVertexData = function () {
  32533. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32534. };
  32535. GroundGeometry.prototype.copy = function (id) {
  32536. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32537. };
  32538. GroundGeometry.prototype.serialize = function () {
  32539. var serializationObject = _super.prototype.serialize.call(this);
  32540. serializationObject.width = this.width;
  32541. serializationObject.height = this.height;
  32542. serializationObject.subdivisions = this.subdivisions;
  32543. return serializationObject;
  32544. };
  32545. GroundGeometry.Parse = function (parsedGround, scene) {
  32546. if (scene.getGeometryByID(parsedGround.id)) {
  32547. return null; // null since geometry could be something else than a ground...
  32548. }
  32549. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32550. if (BABYLON.Tags) {
  32551. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32552. }
  32553. scene.pushGeometry(ground, true);
  32554. return ground;
  32555. };
  32556. return GroundGeometry;
  32557. }(_PrimitiveGeometry));
  32558. BABYLON.GroundGeometry = GroundGeometry;
  32559. var TiledGroundGeometry = /** @class */ (function (_super) {
  32560. __extends(TiledGroundGeometry, _super);
  32561. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32562. if (mesh === void 0) { mesh = null; }
  32563. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32564. _this.xmin = xmin;
  32565. _this.zmin = zmin;
  32566. _this.xmax = xmax;
  32567. _this.zmax = zmax;
  32568. _this.subdivisions = subdivisions;
  32569. _this.precision = precision;
  32570. return _this;
  32571. }
  32572. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32573. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32574. };
  32575. TiledGroundGeometry.prototype.copy = function (id) {
  32576. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32577. };
  32578. return TiledGroundGeometry;
  32579. }(_PrimitiveGeometry));
  32580. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32581. var PlaneGeometry = /** @class */ (function (_super) {
  32582. __extends(PlaneGeometry, _super);
  32583. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32584. if (mesh === void 0) { mesh = null; }
  32585. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32586. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32587. _this.size = size;
  32588. _this.side = side;
  32589. return _this;
  32590. }
  32591. PlaneGeometry.prototype._regenerateVertexData = function () {
  32592. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32593. };
  32594. PlaneGeometry.prototype.copy = function (id) {
  32595. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32596. };
  32597. PlaneGeometry.prototype.serialize = function () {
  32598. var serializationObject = _super.prototype.serialize.call(this);
  32599. serializationObject.size = this.size;
  32600. return serializationObject;
  32601. };
  32602. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32603. if (scene.getGeometryByID(parsedPlane.id)) {
  32604. return null; // null since geometry could be something else than a ground...
  32605. }
  32606. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32607. if (BABYLON.Tags) {
  32608. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32609. }
  32610. scene.pushGeometry(plane, true);
  32611. return plane;
  32612. };
  32613. return PlaneGeometry;
  32614. }(_PrimitiveGeometry));
  32615. BABYLON.PlaneGeometry = PlaneGeometry;
  32616. var TorusKnotGeometry = /** @class */ (function (_super) {
  32617. __extends(TorusKnotGeometry, _super);
  32618. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32619. if (mesh === void 0) { mesh = null; }
  32620. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32621. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32622. _this.radius = radius;
  32623. _this.tube = tube;
  32624. _this.radialSegments = radialSegments;
  32625. _this.tubularSegments = tubularSegments;
  32626. _this.p = p;
  32627. _this.q = q;
  32628. _this.side = side;
  32629. return _this;
  32630. }
  32631. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32632. 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 });
  32633. };
  32634. TorusKnotGeometry.prototype.copy = function (id) {
  32635. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32636. };
  32637. TorusKnotGeometry.prototype.serialize = function () {
  32638. var serializationObject = _super.prototype.serialize.call(this);
  32639. serializationObject.radius = this.radius;
  32640. serializationObject.tube = this.tube;
  32641. serializationObject.radialSegments = this.radialSegments;
  32642. serializationObject.tubularSegments = this.tubularSegments;
  32643. serializationObject.p = this.p;
  32644. serializationObject.q = this.q;
  32645. return serializationObject;
  32646. };
  32647. ;
  32648. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32649. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32650. return null; // null since geometry could be something else than a ground...
  32651. }
  32652. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32653. if (BABYLON.Tags) {
  32654. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32655. }
  32656. scene.pushGeometry(torusKnot, true);
  32657. return torusKnot;
  32658. };
  32659. return TorusKnotGeometry;
  32660. }(_PrimitiveGeometry));
  32661. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32662. //}
  32663. })(BABYLON || (BABYLON = {}));
  32664. //# sourceMappingURL=babylon.geometry.js.map
  32665. var BABYLON;
  32666. (function (BABYLON) {
  32667. var PostProcessManager = /** @class */ (function () {
  32668. function PostProcessManager(scene) {
  32669. this._vertexBuffers = {};
  32670. this._scene = scene;
  32671. }
  32672. PostProcessManager.prototype._prepareBuffers = function () {
  32673. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32674. return;
  32675. }
  32676. // VBO
  32677. var vertices = [];
  32678. vertices.push(1, 1);
  32679. vertices.push(-1, 1);
  32680. vertices.push(-1, -1);
  32681. vertices.push(1, -1);
  32682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32683. this._buildIndexBuffer();
  32684. };
  32685. PostProcessManager.prototype._buildIndexBuffer = function () {
  32686. // Indices
  32687. var indices = [];
  32688. indices.push(0);
  32689. indices.push(1);
  32690. indices.push(2);
  32691. indices.push(0);
  32692. indices.push(2);
  32693. indices.push(3);
  32694. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32695. };
  32696. PostProcessManager.prototype._rebuild = function () {
  32697. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32698. if (!vb) {
  32699. return;
  32700. }
  32701. vb._rebuild();
  32702. this._buildIndexBuffer();
  32703. };
  32704. // Methods
  32705. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32706. if (sourceTexture === void 0) { sourceTexture = null; }
  32707. if (postProcesses === void 0) { postProcesses = null; }
  32708. var camera = this._scene.activeCamera;
  32709. if (!camera) {
  32710. return false;
  32711. }
  32712. var postProcesses = postProcesses || camera._postProcesses;
  32713. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32714. return false;
  32715. }
  32716. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32717. return true;
  32718. };
  32719. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32720. if (targetTexture === void 0) { targetTexture = null; }
  32721. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32722. var engine = this._scene.getEngine();
  32723. for (var index = 0; index < postProcesses.length; index++) {
  32724. if (index < postProcesses.length - 1) {
  32725. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32726. }
  32727. else {
  32728. if (targetTexture) {
  32729. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32730. }
  32731. else {
  32732. engine.restoreDefaultFramebuffer();
  32733. }
  32734. }
  32735. var pp = postProcesses[index];
  32736. var effect = pp.apply();
  32737. if (effect) {
  32738. pp.onBeforeRenderObservable.notifyObservers(effect);
  32739. // VBOs
  32740. this._prepareBuffers();
  32741. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32742. // Draw order
  32743. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32744. pp.onAfterRenderObservable.notifyObservers(effect);
  32745. }
  32746. }
  32747. // Restore depth buffer
  32748. engine.setDepthBuffer(true);
  32749. engine.setDepthWrite(true);
  32750. };
  32751. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32752. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32753. var camera = this._scene.activeCamera;
  32754. if (!camera) {
  32755. return;
  32756. }
  32757. postProcesses = postProcesses || camera._postProcesses;
  32758. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32759. return;
  32760. }
  32761. var engine = this._scene.getEngine();
  32762. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32763. if (index < len - 1) {
  32764. postProcesses[index + 1].activate(camera, targetTexture);
  32765. }
  32766. else {
  32767. if (targetTexture) {
  32768. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32769. }
  32770. else {
  32771. engine.restoreDefaultFramebuffer();
  32772. }
  32773. }
  32774. if (doNotPresent) {
  32775. break;
  32776. }
  32777. var pp = postProcesses[index];
  32778. var effect = pp.apply();
  32779. if (effect) {
  32780. pp.onBeforeRenderObservable.notifyObservers(effect);
  32781. // VBOs
  32782. this._prepareBuffers();
  32783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32784. // Draw order
  32785. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32786. pp.onAfterRenderObservable.notifyObservers(effect);
  32787. }
  32788. }
  32789. // Restore states
  32790. engine.setDepthBuffer(true);
  32791. engine.setDepthWrite(true);
  32792. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32793. };
  32794. PostProcessManager.prototype.dispose = function () {
  32795. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32796. if (buffer) {
  32797. buffer.dispose();
  32798. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32799. }
  32800. if (this._indexBuffer) {
  32801. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32802. this._indexBuffer = null;
  32803. }
  32804. };
  32805. return PostProcessManager;
  32806. }());
  32807. BABYLON.PostProcessManager = PostProcessManager;
  32808. })(BABYLON || (BABYLON = {}));
  32809. //# sourceMappingURL=babylon.postProcessManager.js.map
  32810. var BABYLON;
  32811. (function (BABYLON) {
  32812. /**
  32813. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32814. */
  32815. var PerformanceMonitor = /** @class */ (function () {
  32816. /**
  32817. * constructor
  32818. * @param frameSampleSize The number of samples required to saturate the sliding window
  32819. */
  32820. function PerformanceMonitor(frameSampleSize) {
  32821. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32822. this._enabled = true;
  32823. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32824. }
  32825. /**
  32826. * Samples current frame
  32827. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32828. */
  32829. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32830. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32831. if (!this._enabled)
  32832. return;
  32833. if (this._lastFrameTimeMs != null) {
  32834. var dt = timeMs - this._lastFrameTimeMs;
  32835. this._rollingFrameTime.add(dt);
  32836. }
  32837. this._lastFrameTimeMs = timeMs;
  32838. };
  32839. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32840. /**
  32841. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32842. * @return Average frame time in milliseconds
  32843. */
  32844. get: function () {
  32845. return this._rollingFrameTime.average;
  32846. },
  32847. enumerable: true,
  32848. configurable: true
  32849. });
  32850. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32851. /**
  32852. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32853. * @return Frame time variance in milliseconds squared
  32854. */
  32855. get: function () {
  32856. return this._rollingFrameTime.variance;
  32857. },
  32858. enumerable: true,
  32859. configurable: true
  32860. });
  32861. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32862. /**
  32863. * Returns the frame time of the most recent frame
  32864. * @return Frame time in milliseconds
  32865. */
  32866. get: function () {
  32867. return this._rollingFrameTime.history(0);
  32868. },
  32869. enumerable: true,
  32870. configurable: true
  32871. });
  32872. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32873. /**
  32874. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32875. * @return Framerate in frames per second
  32876. */
  32877. get: function () {
  32878. return 1000.0 / this._rollingFrameTime.average;
  32879. },
  32880. enumerable: true,
  32881. configurable: true
  32882. });
  32883. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32884. /**
  32885. * Returns the average framerate in frames per second using the most recent frame time
  32886. * @return Framerate in frames per second
  32887. */
  32888. get: function () {
  32889. var history = this._rollingFrameTime.history(0);
  32890. if (history === 0) {
  32891. return 0;
  32892. }
  32893. return 1000.0 / history;
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32899. /**
  32900. * Returns true if enough samples have been taken to completely fill the sliding window
  32901. * @return true if saturated
  32902. */
  32903. get: function () {
  32904. return this._rollingFrameTime.isSaturated();
  32905. },
  32906. enumerable: true,
  32907. configurable: true
  32908. });
  32909. /**
  32910. * Enables contributions to the sliding window sample set
  32911. */
  32912. PerformanceMonitor.prototype.enable = function () {
  32913. this._enabled = true;
  32914. };
  32915. /**
  32916. * Disables contributions to the sliding window sample set
  32917. * Samples will not be interpolated over the disabled period
  32918. */
  32919. PerformanceMonitor.prototype.disable = function () {
  32920. this._enabled = false;
  32921. //clear last sample to avoid interpolating over the disabled period when next enabled
  32922. this._lastFrameTimeMs = null;
  32923. };
  32924. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32925. /**
  32926. * Returns true if sampling is enabled
  32927. * @return true if enabled
  32928. */
  32929. get: function () {
  32930. return this._enabled;
  32931. },
  32932. enumerable: true,
  32933. configurable: true
  32934. });
  32935. /**
  32936. * Resets performance monitor
  32937. */
  32938. PerformanceMonitor.prototype.reset = function () {
  32939. //clear last sample to avoid interpolating over the disabled period when next enabled
  32940. this._lastFrameTimeMs = null;
  32941. //wipe record
  32942. this._rollingFrameTime.reset();
  32943. };
  32944. return PerformanceMonitor;
  32945. }());
  32946. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32947. /**
  32948. * RollingAverage
  32949. *
  32950. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32951. */
  32952. var RollingAverage = /** @class */ (function () {
  32953. /**
  32954. * constructor
  32955. * @param length The number of samples required to saturate the sliding window
  32956. */
  32957. function RollingAverage(length) {
  32958. this._samples = new Array(length);
  32959. this.reset();
  32960. }
  32961. /**
  32962. * Adds a sample to the sample set
  32963. * @param v The sample value
  32964. */
  32965. RollingAverage.prototype.add = function (v) {
  32966. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32967. var delta;
  32968. //we need to check if we've already wrapped round
  32969. if (this.isSaturated()) {
  32970. //remove bottom of stack from mean
  32971. var bottomValue = this._samples[this._pos];
  32972. delta = bottomValue - this.average;
  32973. this.average -= delta / (this._sampleCount - 1);
  32974. this._m2 -= delta * (bottomValue - this.average);
  32975. }
  32976. else {
  32977. this._sampleCount++;
  32978. }
  32979. //add new value to mean
  32980. delta = v - this.average;
  32981. this.average += delta / (this._sampleCount);
  32982. this._m2 += delta * (v - this.average);
  32983. //set the new variance
  32984. this.variance = this._m2 / (this._sampleCount - 1);
  32985. this._samples[this._pos] = v;
  32986. this._pos++;
  32987. this._pos %= this._samples.length; //positive wrap around
  32988. };
  32989. /**
  32990. * Returns previously added values or null if outside of history or outside the sliding window domain
  32991. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32992. * @return Value previously recorded with add() or null if outside of range
  32993. */
  32994. RollingAverage.prototype.history = function (i) {
  32995. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32996. return 0;
  32997. }
  32998. var i0 = this._wrapPosition(this._pos - 1.0);
  32999. return this._samples[this._wrapPosition(i0 - i)];
  33000. };
  33001. /**
  33002. * Returns true if enough samples have been taken to completely fill the sliding window
  33003. * @return true if sample-set saturated
  33004. */
  33005. RollingAverage.prototype.isSaturated = function () {
  33006. return this._sampleCount >= this._samples.length;
  33007. };
  33008. /**
  33009. * Resets the rolling average (equivalent to 0 samples taken so far)
  33010. */
  33011. RollingAverage.prototype.reset = function () {
  33012. this.average = 0;
  33013. this.variance = 0;
  33014. this._sampleCount = 0;
  33015. this._pos = 0;
  33016. this._m2 = 0;
  33017. };
  33018. /**
  33019. * Wraps a value around the sample range boundaries
  33020. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33021. * @return Wrapped position in sample range
  33022. */
  33023. RollingAverage.prototype._wrapPosition = function (i) {
  33024. var max = this._samples.length;
  33025. return ((i % max) + max) % max;
  33026. };
  33027. return RollingAverage;
  33028. }());
  33029. BABYLON.RollingAverage = RollingAverage;
  33030. })(BABYLON || (BABYLON = {}));
  33031. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33032. var BABYLON;
  33033. (function (BABYLON) {
  33034. /**
  33035. * This groups together the common properties used for image processing either in direct forward pass
  33036. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33037. * or not.
  33038. */
  33039. var ImageProcessingConfiguration = /** @class */ (function () {
  33040. function ImageProcessingConfiguration() {
  33041. /**
  33042. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33043. */
  33044. this.colorCurves = new BABYLON.ColorCurves();
  33045. this._colorCurvesEnabled = false;
  33046. this._colorGradingEnabled = false;
  33047. this._colorGradingWithGreenDepth = true;
  33048. this._colorGradingBGR = true;
  33049. this._exposure = 1.0;
  33050. this._toneMappingEnabled = false;
  33051. this._contrast = 1.0;
  33052. /**
  33053. * Vignette stretch size.
  33054. */
  33055. this.vignetteStretch = 0;
  33056. /**
  33057. * Vignette centre X Offset.
  33058. */
  33059. this.vignetteCentreX = 0;
  33060. /**
  33061. * Vignette centre Y Offset.
  33062. */
  33063. this.vignetteCentreY = 0;
  33064. /**
  33065. * Vignette weight or intensity of the vignette effect.
  33066. */
  33067. this.vignetteWeight = 1.5;
  33068. /**
  33069. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33070. * if vignetteEnabled is set to true.
  33071. */
  33072. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33073. /**
  33074. * Camera field of view used by the Vignette effect.
  33075. */
  33076. this.vignetteCameraFov = 0.5;
  33077. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33078. this._vignetteEnabled = false;
  33079. this._applyByPostProcess = false;
  33080. this._isEnabled = true;
  33081. /**
  33082. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33083. * @type {BABYLON.Observable}
  33084. */
  33085. this.onUpdateParameters = new BABYLON.Observable();
  33086. }
  33087. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33088. /**
  33089. * Gets wether the color curves effect is enabled.
  33090. */
  33091. get: function () {
  33092. return this._colorCurvesEnabled;
  33093. },
  33094. /**
  33095. * Sets wether the color curves effect is enabled.
  33096. */
  33097. set: function (value) {
  33098. if (this._colorCurvesEnabled === value) {
  33099. return;
  33100. }
  33101. this._colorCurvesEnabled = value;
  33102. this._updateParameters();
  33103. },
  33104. enumerable: true,
  33105. configurable: true
  33106. });
  33107. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33108. /**
  33109. * Gets wether the color grading effect is enabled.
  33110. */
  33111. get: function () {
  33112. return this._colorGradingEnabled;
  33113. },
  33114. /**
  33115. * Sets wether the color grading effect is enabled.
  33116. */
  33117. set: function (value) {
  33118. if (this._colorGradingEnabled === value) {
  33119. return;
  33120. }
  33121. this._colorGradingEnabled = value;
  33122. this._updateParameters();
  33123. },
  33124. enumerable: true,
  33125. configurable: true
  33126. });
  33127. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33128. /**
  33129. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33130. */
  33131. get: function () {
  33132. return this._colorGradingWithGreenDepth;
  33133. },
  33134. /**
  33135. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33136. */
  33137. set: function (value) {
  33138. if (this._colorGradingWithGreenDepth === value) {
  33139. return;
  33140. }
  33141. this._colorGradingWithGreenDepth = value;
  33142. this._updateParameters();
  33143. },
  33144. enumerable: true,
  33145. configurable: true
  33146. });
  33147. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33148. /**
  33149. * Gets wether the color grading texture contains BGR values.
  33150. */
  33151. get: function () {
  33152. return this._colorGradingBGR;
  33153. },
  33154. /**
  33155. * Sets wether the color grading texture contains BGR values.
  33156. */
  33157. set: function (value) {
  33158. if (this._colorGradingBGR === value) {
  33159. return;
  33160. }
  33161. this._colorGradingBGR = value;
  33162. this._updateParameters();
  33163. },
  33164. enumerable: true,
  33165. configurable: true
  33166. });
  33167. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33168. /**
  33169. * Gets the Exposure used in the effect.
  33170. */
  33171. get: function () {
  33172. return this._exposure;
  33173. },
  33174. /**
  33175. * Sets the Exposure used in the effect.
  33176. */
  33177. set: function (value) {
  33178. if (this._exposure === value) {
  33179. return;
  33180. }
  33181. this._exposure = value;
  33182. this._updateParameters();
  33183. },
  33184. enumerable: true,
  33185. configurable: true
  33186. });
  33187. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33188. /**
  33189. * Gets wether the tone mapping effect is enabled.
  33190. */
  33191. get: function () {
  33192. return this._toneMappingEnabled;
  33193. },
  33194. /**
  33195. * Sets wether the tone mapping effect is enabled.
  33196. */
  33197. set: function (value) {
  33198. if (this._toneMappingEnabled === value) {
  33199. return;
  33200. }
  33201. this._toneMappingEnabled = value;
  33202. this._updateParameters();
  33203. },
  33204. enumerable: true,
  33205. configurable: true
  33206. });
  33207. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33208. /**
  33209. * Gets the contrast used in the effect.
  33210. */
  33211. get: function () {
  33212. return this._contrast;
  33213. },
  33214. /**
  33215. * Sets the contrast used in the effect.
  33216. */
  33217. set: function (value) {
  33218. if (this._contrast === value) {
  33219. return;
  33220. }
  33221. this._contrast = value;
  33222. this._updateParameters();
  33223. },
  33224. enumerable: true,
  33225. configurable: true
  33226. });
  33227. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33228. /**
  33229. * Gets the vignette blend mode allowing different kind of effect.
  33230. */
  33231. get: function () {
  33232. return this._vignetteBlendMode;
  33233. },
  33234. /**
  33235. * Sets the vignette blend mode allowing different kind of effect.
  33236. */
  33237. set: function (value) {
  33238. if (this._vignetteBlendMode === value) {
  33239. return;
  33240. }
  33241. this._vignetteBlendMode = value;
  33242. this._updateParameters();
  33243. },
  33244. enumerable: true,
  33245. configurable: true
  33246. });
  33247. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33248. /**
  33249. * Gets wether the vignette effect is enabled.
  33250. */
  33251. get: function () {
  33252. return this._vignetteEnabled;
  33253. },
  33254. /**
  33255. * Sets wether the vignette effect is enabled.
  33256. */
  33257. set: function (value) {
  33258. if (this._vignetteEnabled === value) {
  33259. return;
  33260. }
  33261. this._vignetteEnabled = value;
  33262. this._updateParameters();
  33263. },
  33264. enumerable: true,
  33265. configurable: true
  33266. });
  33267. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33268. /**
  33269. * Gets wether the image processing is applied through a post process or not.
  33270. */
  33271. get: function () {
  33272. return this._applyByPostProcess;
  33273. },
  33274. /**
  33275. * Sets wether the image processing is applied through a post process or not.
  33276. */
  33277. set: function (value) {
  33278. if (this._applyByPostProcess === value) {
  33279. return;
  33280. }
  33281. this._applyByPostProcess = value;
  33282. this._updateParameters();
  33283. },
  33284. enumerable: true,
  33285. configurable: true
  33286. });
  33287. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33288. /**
  33289. * Gets wether the image processing is enabled or not.
  33290. */
  33291. get: function () {
  33292. return this._isEnabled;
  33293. },
  33294. /**
  33295. * Sets wether the image processing is enabled or not.
  33296. */
  33297. set: function (value) {
  33298. if (this._isEnabled === value) {
  33299. return;
  33300. }
  33301. this._isEnabled = value;
  33302. this._updateParameters();
  33303. },
  33304. enumerable: true,
  33305. configurable: true
  33306. });
  33307. /**
  33308. * Method called each time the image processing information changes requires to recompile the effect.
  33309. */
  33310. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33311. this.onUpdateParameters.notifyObservers(this);
  33312. };
  33313. ImageProcessingConfiguration.prototype.getClassName = function () {
  33314. return "ImageProcessingConfiguration";
  33315. };
  33316. /**
  33317. * Prepare the list of uniforms associated with the Image Processing effects.
  33318. * @param uniformsList The list of uniforms used in the effect
  33319. * @param defines the list of defines currently in use
  33320. */
  33321. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33322. if (defines.EXPOSURE) {
  33323. uniforms.push("exposureLinear");
  33324. }
  33325. if (defines.CONTRAST) {
  33326. uniforms.push("contrast");
  33327. }
  33328. if (defines.COLORGRADING) {
  33329. uniforms.push("colorTransformSettings");
  33330. }
  33331. if (defines.VIGNETTE) {
  33332. uniforms.push("vInverseScreenSize");
  33333. uniforms.push("vignetteSettings1");
  33334. uniforms.push("vignetteSettings2");
  33335. }
  33336. if (defines.COLORCURVES) {
  33337. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33338. }
  33339. };
  33340. /**
  33341. * Prepare the list of samplers associated with the Image Processing effects.
  33342. * @param uniformsList The list of uniforms used in the effect
  33343. * @param defines the list of defines currently in use
  33344. */
  33345. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33346. if (defines.COLORGRADING) {
  33347. samplersList.push("txColorTransform");
  33348. }
  33349. };
  33350. /**
  33351. * Prepare the list of defines associated to the shader.
  33352. * @param defines the list of defines to complete
  33353. */
  33354. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33355. if (forPostProcess === void 0) { forPostProcess = false; }
  33356. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33357. defines.VIGNETTE = false;
  33358. defines.TONEMAPPING = false;
  33359. defines.CONTRAST = false;
  33360. defines.EXPOSURE = false;
  33361. defines.COLORCURVES = false;
  33362. defines.COLORGRADING = false;
  33363. defines.COLORGRADING3D = false;
  33364. defines.IMAGEPROCESSING = false;
  33365. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33366. return;
  33367. }
  33368. defines.VIGNETTE = this.vignetteEnabled;
  33369. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33370. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33371. defines.TONEMAPPING = this.toneMappingEnabled;
  33372. defines.CONTRAST = (this.contrast !== 1.0);
  33373. defines.EXPOSURE = (this.exposure !== 1.0);
  33374. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33375. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33376. if (defines.COLORGRADING) {
  33377. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33378. }
  33379. else {
  33380. defines.COLORGRADING3D = false;
  33381. }
  33382. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33383. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33384. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33385. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33386. };
  33387. /**
  33388. * Returns true if all the image processing information are ready.
  33389. */
  33390. ImageProcessingConfiguration.prototype.isReady = function () {
  33391. // Color Grading texure can not be none blocking.
  33392. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33393. };
  33394. /**
  33395. * Binds the image processing to the shader.
  33396. * @param effect The effect to bind to
  33397. */
  33398. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33399. if (aspectRatio === void 0) { aspectRatio = 1; }
  33400. // Color Curves
  33401. if (this._colorCurvesEnabled && this.colorCurves) {
  33402. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33403. }
  33404. // Vignette
  33405. if (this._vignetteEnabled) {
  33406. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33407. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33408. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33409. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33410. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33411. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33412. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33413. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33414. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33415. var vignettePower = -2.0 * this.vignetteWeight;
  33416. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33417. }
  33418. // Exposure
  33419. effect.setFloat("exposureLinear", this.exposure);
  33420. // Contrast
  33421. effect.setFloat("contrast", this.contrast);
  33422. // Color transform settings
  33423. if (this.colorGradingTexture) {
  33424. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33425. var textureSize = this.colorGradingTexture.getSize().height;
  33426. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33427. 0.5 / textureSize, // textureOffset
  33428. textureSize, // textureSize
  33429. this.colorGradingTexture.level // weight
  33430. );
  33431. }
  33432. };
  33433. /**
  33434. * Clones the current image processing instance.
  33435. * @return The cloned image processing
  33436. */
  33437. ImageProcessingConfiguration.prototype.clone = function () {
  33438. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33439. };
  33440. /**
  33441. * Serializes the current image processing instance to a json representation.
  33442. * @return a JSON representation
  33443. */
  33444. ImageProcessingConfiguration.prototype.serialize = function () {
  33445. return BABYLON.SerializationHelper.Serialize(this);
  33446. };
  33447. /**
  33448. * Parses the image processing from a json representation.
  33449. * @param source the JSON source to parse
  33450. * @return The parsed image processing
  33451. */
  33452. ImageProcessingConfiguration.Parse = function (source) {
  33453. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33454. };
  33455. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33456. /**
  33457. * Used to apply the vignette as a mix with the pixel color.
  33458. */
  33459. get: function () {
  33460. return this._VIGNETTEMODE_MULTIPLY;
  33461. },
  33462. enumerable: true,
  33463. configurable: true
  33464. });
  33465. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33466. /**
  33467. * Used to apply the vignette as a replacement of the pixel color.
  33468. */
  33469. get: function () {
  33470. return this._VIGNETTEMODE_OPAQUE;
  33471. },
  33472. enumerable: true,
  33473. configurable: true
  33474. });
  33475. // Static constants associated to the image processing.
  33476. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33477. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33478. __decorate([
  33479. BABYLON.serializeAsColorCurves()
  33480. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33481. __decorate([
  33482. BABYLON.serialize()
  33483. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33484. __decorate([
  33485. BABYLON.serializeAsTexture()
  33486. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33487. __decorate([
  33488. BABYLON.serialize()
  33489. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33490. __decorate([
  33491. BABYLON.serialize()
  33492. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33493. __decorate([
  33494. BABYLON.serialize()
  33495. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33496. __decorate([
  33497. BABYLON.serialize()
  33498. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33499. __decorate([
  33500. BABYLON.serialize()
  33501. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33502. __decorate([
  33503. BABYLON.serialize()
  33504. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33505. __decorate([
  33506. BABYLON.serialize()
  33507. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33508. __decorate([
  33509. BABYLON.serialize()
  33510. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33511. __decorate([
  33512. BABYLON.serialize()
  33513. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33514. __decorate([
  33515. BABYLON.serialize()
  33516. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33517. __decorate([
  33518. BABYLON.serializeAsColor4()
  33519. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33520. __decorate([
  33521. BABYLON.serialize()
  33522. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33523. __decorate([
  33524. BABYLON.serialize()
  33525. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33526. __decorate([
  33527. BABYLON.serialize()
  33528. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33529. __decorate([
  33530. BABYLON.serialize()
  33531. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33532. __decorate([
  33533. BABYLON.serialize()
  33534. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33535. return ImageProcessingConfiguration;
  33536. }());
  33537. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33538. })(BABYLON || (BABYLON = {}));
  33539. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33540. var BABYLON;
  33541. (function (BABYLON) {
  33542. /**
  33543. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33544. * It can help converting any input color in a desired output one. This can then be used to create effects
  33545. * from sepia, black and white to sixties or futuristic rendering...
  33546. *
  33547. * The only supported format is currently 3dl.
  33548. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33549. */
  33550. var ColorGradingTexture = /** @class */ (function (_super) {
  33551. __extends(ColorGradingTexture, _super);
  33552. /**
  33553. * Instantiates a ColorGradingTexture from the following parameters.
  33554. *
  33555. * @param url The location of the color gradind data (currently only supporting 3dl)
  33556. * @param scene The scene the texture will be used in
  33557. */
  33558. function ColorGradingTexture(url, scene) {
  33559. var _this = _super.call(this, scene) || this;
  33560. if (!url) {
  33561. return _this;
  33562. }
  33563. _this._engine = scene.getEngine();
  33564. _this._textureMatrix = BABYLON.Matrix.Identity();
  33565. _this.name = url;
  33566. _this.url = url;
  33567. _this.hasAlpha = false;
  33568. _this.isCube = false;
  33569. _this.is3D = _this._engine.webGLVersion > 1;
  33570. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33571. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33572. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33573. _this.anisotropicFilteringLevel = 1;
  33574. _this._texture = _this._getFromCache(url, true);
  33575. if (!_this._texture) {
  33576. if (!scene.useDelayedTextureLoading) {
  33577. _this.loadTexture();
  33578. }
  33579. else {
  33580. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33581. }
  33582. }
  33583. return _this;
  33584. }
  33585. /**
  33586. * Returns the texture matrix used in most of the material.
  33587. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33588. */
  33589. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33590. return this._textureMatrix;
  33591. };
  33592. /**
  33593. * Occurs when the file being loaded is a .3dl LUT file.
  33594. */
  33595. ColorGradingTexture.prototype.load3dlTexture = function () {
  33596. var engine = this._engine;
  33597. var texture;
  33598. if (engine.webGLVersion === 1) {
  33599. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33600. }
  33601. else {
  33602. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33603. }
  33604. this._texture = texture;
  33605. var callback = function (text) {
  33606. if (typeof text !== "string") {
  33607. return;
  33608. }
  33609. var data = null;
  33610. var tempData = null;
  33611. var line;
  33612. var lines = text.split('\n');
  33613. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33614. var maxColor = 0;
  33615. for (var i = 0; i < lines.length; i++) {
  33616. line = lines[i];
  33617. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33618. continue;
  33619. if (line.indexOf('#') === 0)
  33620. continue;
  33621. var words = line.split(" ");
  33622. if (size === 0) {
  33623. // Number of space + one
  33624. size = words.length;
  33625. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33626. tempData = new Float32Array(size * size * size * 4);
  33627. continue;
  33628. }
  33629. if (size != 0) {
  33630. var r = Math.max(parseInt(words[0]), 0);
  33631. var g = Math.max(parseInt(words[1]), 0);
  33632. var b = Math.max(parseInt(words[2]), 0);
  33633. maxColor = Math.max(r, maxColor);
  33634. maxColor = Math.max(g, maxColor);
  33635. maxColor = Math.max(b, maxColor);
  33636. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33637. if (tempData) {
  33638. tempData[pixelStorageIndex + 0] = r;
  33639. tempData[pixelStorageIndex + 1] = g;
  33640. tempData[pixelStorageIndex + 2] = b;
  33641. }
  33642. pixelIndexSlice++;
  33643. if (pixelIndexSlice % size == 0) {
  33644. pixelIndexH++;
  33645. pixelIndexSlice = 0;
  33646. if (pixelIndexH % size == 0) {
  33647. pixelIndexW++;
  33648. pixelIndexH = 0;
  33649. }
  33650. }
  33651. }
  33652. }
  33653. if (tempData && data) {
  33654. for (var i = 0; i < tempData.length; i++) {
  33655. if (i > 0 && (i + 1) % 4 === 0) {
  33656. data[i] = 255;
  33657. }
  33658. else {
  33659. var value = tempData[i];
  33660. data[i] = (value / maxColor * 255);
  33661. }
  33662. }
  33663. }
  33664. if (texture.is3D) {
  33665. texture.updateSize(size, size, size);
  33666. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33667. }
  33668. else {
  33669. texture.updateSize(size * size, size);
  33670. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33671. }
  33672. };
  33673. var scene = this.getScene();
  33674. if (scene) {
  33675. scene._loadFile(this.url, callback);
  33676. }
  33677. else {
  33678. this._engine._loadFile(this.url, callback);
  33679. }
  33680. return this._texture;
  33681. };
  33682. /**
  33683. * Starts the loading process of the texture.
  33684. */
  33685. ColorGradingTexture.prototype.loadTexture = function () {
  33686. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33687. this.load3dlTexture();
  33688. }
  33689. };
  33690. /**
  33691. * Clones the color gradind texture.
  33692. */
  33693. ColorGradingTexture.prototype.clone = function () {
  33694. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33695. // Base texture
  33696. newTexture.level = this.level;
  33697. return newTexture;
  33698. };
  33699. /**
  33700. * Called during delayed load for textures.
  33701. */
  33702. ColorGradingTexture.prototype.delayLoad = function () {
  33703. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33704. return;
  33705. }
  33706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33707. this._texture = this._getFromCache(this.url, true);
  33708. if (!this._texture) {
  33709. this.loadTexture();
  33710. }
  33711. };
  33712. /**
  33713. * Parses a color grading texture serialized by Babylon.
  33714. * @param parsedTexture The texture information being parsedTexture
  33715. * @param scene The scene to load the texture in
  33716. * @param rootUrl The root url of the data assets to load
  33717. * @return A color gradind texture
  33718. */
  33719. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33720. var texture = null;
  33721. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33722. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33723. texture.name = parsedTexture.name;
  33724. texture.level = parsedTexture.level;
  33725. }
  33726. return texture;
  33727. };
  33728. /**
  33729. * Serializes the LUT texture to json format.
  33730. */
  33731. ColorGradingTexture.prototype.serialize = function () {
  33732. if (!this.name) {
  33733. return null;
  33734. }
  33735. var serializationObject = {};
  33736. serializationObject.name = this.name;
  33737. serializationObject.level = this.level;
  33738. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33739. return serializationObject;
  33740. };
  33741. /**
  33742. * Empty line regex stored for GC.
  33743. */
  33744. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33745. return ColorGradingTexture;
  33746. }(BABYLON.BaseTexture));
  33747. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33748. })(BABYLON || (BABYLON = {}));
  33749. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33750. var BABYLON;
  33751. (function (BABYLON) {
  33752. /**
  33753. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33754. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33755. * 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;
  33756. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33757. */
  33758. var ColorCurves = /** @class */ (function () {
  33759. function ColorCurves() {
  33760. this._dirty = true;
  33761. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33762. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33763. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33764. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33765. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33766. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33767. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33768. this._globalHue = 30;
  33769. this._globalDensity = 0;
  33770. this._globalSaturation = 0;
  33771. this._globalExposure = 0;
  33772. this._highlightsHue = 30;
  33773. this._highlightsDensity = 0;
  33774. this._highlightsSaturation = 0;
  33775. this._highlightsExposure = 0;
  33776. this._midtonesHue = 30;
  33777. this._midtonesDensity = 0;
  33778. this._midtonesSaturation = 0;
  33779. this._midtonesExposure = 0;
  33780. this._shadowsHue = 30;
  33781. this._shadowsDensity = 0;
  33782. this._shadowsSaturation = 0;
  33783. this._shadowsExposure = 0;
  33784. }
  33785. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33786. /**
  33787. * Gets the global Hue value.
  33788. * 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).
  33789. */
  33790. get: function () {
  33791. return this._globalHue;
  33792. },
  33793. /**
  33794. * Sets the global Hue value.
  33795. * 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).
  33796. */
  33797. set: function (value) {
  33798. this._globalHue = value;
  33799. this._dirty = true;
  33800. },
  33801. enumerable: true,
  33802. configurable: true
  33803. });
  33804. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33805. /**
  33806. * Gets the global Density value.
  33807. * 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.
  33808. * Values less than zero provide a filter of opposite hue.
  33809. */
  33810. get: function () {
  33811. return this._globalDensity;
  33812. },
  33813. /**
  33814. * Sets the global Density value.
  33815. * 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.
  33816. * Values less than zero provide a filter of opposite hue.
  33817. */
  33818. set: function (value) {
  33819. this._globalDensity = value;
  33820. this._dirty = true;
  33821. },
  33822. enumerable: true,
  33823. configurable: true
  33824. });
  33825. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33826. /**
  33827. * Gets the global Saturation value.
  33828. * 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.
  33829. */
  33830. get: function () {
  33831. return this._globalSaturation;
  33832. },
  33833. /**
  33834. * Sets the global Saturation value.
  33835. * 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.
  33836. */
  33837. set: function (value) {
  33838. this._globalSaturation = value;
  33839. this._dirty = true;
  33840. },
  33841. enumerable: true,
  33842. configurable: true
  33843. });
  33844. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33845. /**
  33846. * Gets the highlights Hue value.
  33847. * 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).
  33848. */
  33849. get: function () {
  33850. return this._highlightsHue;
  33851. },
  33852. /**
  33853. * Sets the highlights Hue value.
  33854. * 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).
  33855. */
  33856. set: function (value) {
  33857. this._highlightsHue = value;
  33858. this._dirty = true;
  33859. },
  33860. enumerable: true,
  33861. configurable: true
  33862. });
  33863. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33864. /**
  33865. * Gets the highlights Density value.
  33866. * 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.
  33867. * Values less than zero provide a filter of opposite hue.
  33868. */
  33869. get: function () {
  33870. return this._highlightsDensity;
  33871. },
  33872. /**
  33873. * Sets the highlights Density value.
  33874. * 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.
  33875. * Values less than zero provide a filter of opposite hue.
  33876. */
  33877. set: function (value) {
  33878. this._highlightsDensity = value;
  33879. this._dirty = true;
  33880. },
  33881. enumerable: true,
  33882. configurable: true
  33883. });
  33884. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33885. /**
  33886. * Gets the highlights Saturation value.
  33887. * 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.
  33888. */
  33889. get: function () {
  33890. return this._highlightsSaturation;
  33891. },
  33892. /**
  33893. * Sets the highlights Saturation value.
  33894. * 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.
  33895. */
  33896. set: function (value) {
  33897. this._highlightsSaturation = value;
  33898. this._dirty = true;
  33899. },
  33900. enumerable: true,
  33901. configurable: true
  33902. });
  33903. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33904. /**
  33905. * Gets the highlights Exposure value.
  33906. * 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.
  33907. */
  33908. get: function () {
  33909. return this._highlightsExposure;
  33910. },
  33911. /**
  33912. * Sets the highlights Exposure value.
  33913. * 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.
  33914. */
  33915. set: function (value) {
  33916. this._highlightsExposure = value;
  33917. this._dirty = true;
  33918. },
  33919. enumerable: true,
  33920. configurable: true
  33921. });
  33922. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33923. /**
  33924. * Gets the midtones Hue value.
  33925. * 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).
  33926. */
  33927. get: function () {
  33928. return this._midtonesHue;
  33929. },
  33930. /**
  33931. * Sets the midtones Hue value.
  33932. * 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).
  33933. */
  33934. set: function (value) {
  33935. this._midtonesHue = value;
  33936. this._dirty = true;
  33937. },
  33938. enumerable: true,
  33939. configurable: true
  33940. });
  33941. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33942. /**
  33943. * Gets the midtones Density value.
  33944. * 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.
  33945. * Values less than zero provide a filter of opposite hue.
  33946. */
  33947. get: function () {
  33948. return this._midtonesDensity;
  33949. },
  33950. /**
  33951. * Sets the midtones Density value.
  33952. * 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.
  33953. * Values less than zero provide a filter of opposite hue.
  33954. */
  33955. set: function (value) {
  33956. this._midtonesDensity = value;
  33957. this._dirty = true;
  33958. },
  33959. enumerable: true,
  33960. configurable: true
  33961. });
  33962. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33963. /**
  33964. * Gets the midtones Saturation value.
  33965. * 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.
  33966. */
  33967. get: function () {
  33968. return this._midtonesSaturation;
  33969. },
  33970. /**
  33971. * Sets the midtones Saturation value.
  33972. * 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.
  33973. */
  33974. set: function (value) {
  33975. this._midtonesSaturation = value;
  33976. this._dirty = true;
  33977. },
  33978. enumerable: true,
  33979. configurable: true
  33980. });
  33981. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33982. /**
  33983. * Gets the midtones Exposure value.
  33984. * 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.
  33985. */
  33986. get: function () {
  33987. return this._midtonesExposure;
  33988. },
  33989. /**
  33990. * Sets the midtones Exposure value.
  33991. * 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.
  33992. */
  33993. set: function (value) {
  33994. this._midtonesExposure = value;
  33995. this._dirty = true;
  33996. },
  33997. enumerable: true,
  33998. configurable: true
  33999. });
  34000. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34001. /**
  34002. * Gets the shadows Hue value.
  34003. * 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).
  34004. */
  34005. get: function () {
  34006. return this._shadowsHue;
  34007. },
  34008. /**
  34009. * Sets the shadows Hue value.
  34010. * 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).
  34011. */
  34012. set: function (value) {
  34013. this._shadowsHue = value;
  34014. this._dirty = true;
  34015. },
  34016. enumerable: true,
  34017. configurable: true
  34018. });
  34019. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34020. /**
  34021. * Gets the shadows Density value.
  34022. * 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.
  34023. * Values less than zero provide a filter of opposite hue.
  34024. */
  34025. get: function () {
  34026. return this._shadowsDensity;
  34027. },
  34028. /**
  34029. * Sets the shadows Density value.
  34030. * 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.
  34031. * Values less than zero provide a filter of opposite hue.
  34032. */
  34033. set: function (value) {
  34034. this._shadowsDensity = value;
  34035. this._dirty = true;
  34036. },
  34037. enumerable: true,
  34038. configurable: true
  34039. });
  34040. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34041. /**
  34042. * Gets the shadows Saturation value.
  34043. * 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.
  34044. */
  34045. get: function () {
  34046. return this._shadowsSaturation;
  34047. },
  34048. /**
  34049. * Sets the shadows Saturation value.
  34050. * 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.
  34051. */
  34052. set: function (value) {
  34053. this._shadowsSaturation = value;
  34054. this._dirty = true;
  34055. },
  34056. enumerable: true,
  34057. configurable: true
  34058. });
  34059. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34060. /**
  34061. * Gets the shadows Exposure value.
  34062. * 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.
  34063. */
  34064. get: function () {
  34065. return this._shadowsExposure;
  34066. },
  34067. /**
  34068. * Sets the shadows Exposure value.
  34069. * 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.
  34070. */
  34071. set: function (value) {
  34072. this._shadowsExposure = value;
  34073. this._dirty = true;
  34074. },
  34075. enumerable: true,
  34076. configurable: true
  34077. });
  34078. ColorCurves.prototype.getClassName = function () {
  34079. return "ColorCurves";
  34080. };
  34081. /**
  34082. * Binds the color curves to the shader.
  34083. * @param colorCurves The color curve to bind
  34084. * @param effect The effect to bind to
  34085. */
  34086. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34087. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34088. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34089. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34090. if (colorCurves._dirty) {
  34091. colorCurves._dirty = false;
  34092. // Fill in global info.
  34093. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34094. // Compute highlights info.
  34095. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34096. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34097. // Compute midtones info.
  34098. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34099. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34100. // Compute shadows info.
  34101. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34102. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34103. // Compute deltas (neutral is midtones).
  34104. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34105. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34106. }
  34107. if (effect) {
  34108. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34109. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34110. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34111. }
  34112. };
  34113. /**
  34114. * Prepare the list of uniforms associated with the ColorCurves effects.
  34115. * @param uniformsList The list of uniforms used in the effect
  34116. */
  34117. ColorCurves.PrepareUniforms = function (uniformsList) {
  34118. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34119. };
  34120. /**
  34121. * Returns color grading data based on a hue, density, saturation and exposure value.
  34122. * @param filterHue The hue of the color filter.
  34123. * @param filterDensity The density of the color filter.
  34124. * @param saturation The saturation.
  34125. * @param exposure The exposure.
  34126. * @param result The result data container.
  34127. */
  34128. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34129. if (hue == null) {
  34130. return;
  34131. }
  34132. hue = ColorCurves.clamp(hue, 0, 360);
  34133. density = ColorCurves.clamp(density, -100, 100);
  34134. saturation = ColorCurves.clamp(saturation, -100, 100);
  34135. exposure = ColorCurves.clamp(exposure, -100, 100);
  34136. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34137. // so that the maximum filter density is only 50% control. This provides fine control
  34138. // for small values and reasonable range.
  34139. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34140. density *= 0.5;
  34141. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34142. if (density < 0) {
  34143. density *= -1;
  34144. hue = (hue + 180) % 360;
  34145. }
  34146. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34147. result.scaleToRef(2, result);
  34148. result.a = 1 + 0.01 * saturation;
  34149. };
  34150. /**
  34151. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34152. * @param value The input slider value in range [-100,100].
  34153. * @returns Adjusted value.
  34154. */
  34155. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34156. value /= 100;
  34157. var x = Math.abs(value);
  34158. x = Math.pow(x, 2);
  34159. if (value < 0) {
  34160. x *= -1;
  34161. }
  34162. x *= 100;
  34163. return x;
  34164. };
  34165. /**
  34166. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34167. * @param hue The hue (H) input.
  34168. * @param saturation The saturation (S) input.
  34169. * @param brightness The brightness (B) input.
  34170. * @result An RGBA color represented as Vector4.
  34171. */
  34172. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34173. var h = ColorCurves.clamp(hue, 0, 360);
  34174. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34175. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34176. if (s === 0) {
  34177. result.r = v;
  34178. result.g = v;
  34179. result.b = v;
  34180. }
  34181. else {
  34182. // sector 0 to 5
  34183. h /= 60;
  34184. var i = Math.floor(h);
  34185. // fractional part of h
  34186. var f = h - i;
  34187. var p = v * (1 - s);
  34188. var q = v * (1 - s * f);
  34189. var t = v * (1 - s * (1 - f));
  34190. switch (i) {
  34191. case 0:
  34192. result.r = v;
  34193. result.g = t;
  34194. result.b = p;
  34195. break;
  34196. case 1:
  34197. result.r = q;
  34198. result.g = v;
  34199. result.b = p;
  34200. break;
  34201. case 2:
  34202. result.r = p;
  34203. result.g = v;
  34204. result.b = t;
  34205. break;
  34206. case 3:
  34207. result.r = p;
  34208. result.g = q;
  34209. result.b = v;
  34210. break;
  34211. case 4:
  34212. result.r = t;
  34213. result.g = p;
  34214. result.b = v;
  34215. break;
  34216. default:// case 5:
  34217. result.r = v;
  34218. result.g = p;
  34219. result.b = q;
  34220. break;
  34221. }
  34222. }
  34223. result.a = 1;
  34224. };
  34225. /**
  34226. * Returns a value clamped between min and max
  34227. * @param value The value to clamp
  34228. * @param min The minimum of value
  34229. * @param max The maximum of value
  34230. * @returns The clamped value.
  34231. */
  34232. ColorCurves.clamp = function (value, min, max) {
  34233. return Math.min(Math.max(value, min), max);
  34234. };
  34235. /**
  34236. * Clones the current color curve instance.
  34237. * @return The cloned curves
  34238. */
  34239. ColorCurves.prototype.clone = function () {
  34240. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34241. };
  34242. /**
  34243. * Serializes the current color curve instance to a json representation.
  34244. * @return a JSON representation
  34245. */
  34246. ColorCurves.prototype.serialize = function () {
  34247. return BABYLON.SerializationHelper.Serialize(this);
  34248. };
  34249. /**
  34250. * Parses the color curve from a json representation.
  34251. * @param source the JSON source to parse
  34252. * @return The parsed curves
  34253. */
  34254. ColorCurves.Parse = function (source) {
  34255. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34256. };
  34257. __decorate([
  34258. BABYLON.serialize()
  34259. ], ColorCurves.prototype, "_globalHue", void 0);
  34260. __decorate([
  34261. BABYLON.serialize()
  34262. ], ColorCurves.prototype, "_globalDensity", void 0);
  34263. __decorate([
  34264. BABYLON.serialize()
  34265. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34266. __decorate([
  34267. BABYLON.serialize()
  34268. ], ColorCurves.prototype, "_globalExposure", void 0);
  34269. __decorate([
  34270. BABYLON.serialize()
  34271. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34272. __decorate([
  34273. BABYLON.serialize()
  34274. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34275. __decorate([
  34276. BABYLON.serialize()
  34277. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34278. __decorate([
  34279. BABYLON.serialize()
  34280. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34281. __decorate([
  34282. BABYLON.serialize()
  34283. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34284. __decorate([
  34285. BABYLON.serialize()
  34286. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34287. __decorate([
  34288. BABYLON.serialize()
  34289. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34290. __decorate([
  34291. BABYLON.serialize()
  34292. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34293. return ColorCurves;
  34294. }());
  34295. BABYLON.ColorCurves = ColorCurves;
  34296. })(BABYLON || (BABYLON = {}));
  34297. //# sourceMappingURL=babylon.colorCurves.js.map
  34298. //# sourceMappingURL=babylon.behavior.js.map
  34299. var BABYLON;
  34300. (function (BABYLON) {
  34301. var MaterialHelper = /** @class */ (function () {
  34302. function MaterialHelper() {
  34303. }
  34304. MaterialHelper.BindEyePosition = function (effect, scene) {
  34305. if (scene._forcedViewPosition) {
  34306. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34307. return;
  34308. }
  34309. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34310. };
  34311. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34312. defines._needUVs = true;
  34313. defines[key] = true;
  34314. if (texture.getTextureMatrix().isIdentity(true)) {
  34315. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34316. if (texture.coordinatesIndex === 0) {
  34317. defines["MAINUV1"] = true;
  34318. }
  34319. else {
  34320. defines["MAINUV2"] = true;
  34321. }
  34322. }
  34323. else {
  34324. defines[key + "DIRECTUV"] = 0;
  34325. }
  34326. };
  34327. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34328. var matrix = texture.getTextureMatrix();
  34329. if (!matrix.isIdentity(true)) {
  34330. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34331. }
  34332. };
  34333. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34334. if (defines._areMiscDirty) {
  34335. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34336. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34337. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34338. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34339. }
  34340. };
  34341. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34342. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34343. var changed = false;
  34344. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34345. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34346. changed = true;
  34347. }
  34348. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34349. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34350. changed = true;
  34351. }
  34352. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34353. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34354. changed = true;
  34355. }
  34356. if (defines["INSTANCES"] !== useInstances) {
  34357. defines["INSTANCES"] = useInstances;
  34358. changed = true;
  34359. }
  34360. if (changed) {
  34361. defines.markAsUnprocessed();
  34362. }
  34363. };
  34364. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34365. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34366. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34367. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34368. return false;
  34369. }
  34370. defines._normals = defines._needNormals;
  34371. defines._uvs = defines._needUVs;
  34372. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34373. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34374. defines["TANGENT"] = true;
  34375. }
  34376. if (defines._needUVs) {
  34377. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34378. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34379. }
  34380. else {
  34381. defines["UV1"] = false;
  34382. defines["UV2"] = false;
  34383. }
  34384. if (useVertexColor) {
  34385. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34386. defines["VERTEXCOLOR"] = hasVertexColors;
  34387. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34388. }
  34389. if (useBones) {
  34390. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34391. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34392. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34393. }
  34394. else {
  34395. defines["NUM_BONE_INFLUENCERS"] = 0;
  34396. defines["BonesPerMesh"] = 0;
  34397. }
  34398. }
  34399. if (useMorphTargets) {
  34400. var manager = mesh.morphTargetManager;
  34401. if (manager) {
  34402. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34403. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34404. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34405. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34406. }
  34407. else {
  34408. defines["MORPHTARGETS_TANGENT"] = false;
  34409. defines["MORPHTARGETS_NORMAL"] = false;
  34410. defines["MORPHTARGETS"] = false;
  34411. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34412. }
  34413. }
  34414. return true;
  34415. };
  34416. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34417. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34418. if (disableLighting === void 0) { disableLighting = false; }
  34419. if (!defines._areLightsDirty) {
  34420. return defines._needNormals;
  34421. }
  34422. var lightIndex = 0;
  34423. var needNormals = false;
  34424. var needRebuild = false;
  34425. var lightmapMode = false;
  34426. var shadowEnabled = false;
  34427. var specularEnabled = false;
  34428. if (scene.lightsEnabled && !disableLighting) {
  34429. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34430. var light = _a[_i];
  34431. needNormals = true;
  34432. if (defines["LIGHT" + lightIndex] === undefined) {
  34433. needRebuild = true;
  34434. }
  34435. defines["LIGHT" + lightIndex] = true;
  34436. defines["SPOTLIGHT" + lightIndex] = false;
  34437. defines["HEMILIGHT" + lightIndex] = false;
  34438. defines["POINTLIGHT" + lightIndex] = false;
  34439. defines["DIRLIGHT" + lightIndex] = false;
  34440. var type;
  34441. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34442. type = "SPOTLIGHT" + lightIndex;
  34443. }
  34444. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34445. type = "HEMILIGHT" + lightIndex;
  34446. }
  34447. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34448. type = "POINTLIGHT" + lightIndex;
  34449. }
  34450. else {
  34451. type = "DIRLIGHT" + lightIndex;
  34452. }
  34453. defines[type] = true;
  34454. // Specular
  34455. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34456. specularEnabled = true;
  34457. }
  34458. // Shadows
  34459. defines["SHADOW" + lightIndex] = false;
  34460. defines["SHADOWPCF" + lightIndex] = false;
  34461. defines["SHADOWESM" + lightIndex] = false;
  34462. defines["SHADOWCUBE" + lightIndex] = false;
  34463. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34464. var shadowGenerator = light.getShadowGenerator();
  34465. if (shadowGenerator) {
  34466. shadowEnabled = true;
  34467. shadowGenerator.prepareDefines(defines, lightIndex);
  34468. }
  34469. }
  34470. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34471. lightmapMode = true;
  34472. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34473. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34474. }
  34475. else {
  34476. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34477. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34478. }
  34479. lightIndex++;
  34480. if (lightIndex === maxSimultaneousLights)
  34481. break;
  34482. }
  34483. }
  34484. defines["SPECULARTERM"] = specularEnabled;
  34485. defines["SHADOWS"] = shadowEnabled;
  34486. // Resetting all other lights if any
  34487. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34488. if (defines["LIGHT" + index] !== undefined) {
  34489. defines["LIGHT" + index] = false;
  34490. defines["HEMILIGHT" + lightIndex] = false;
  34491. defines["POINTLIGHT" + lightIndex] = false;
  34492. defines["DIRLIGHT" + lightIndex] = false;
  34493. defines["SPOTLIGHT" + lightIndex] = false;
  34494. defines["SHADOW" + lightIndex] = false;
  34495. }
  34496. }
  34497. var caps = scene.getEngine().getCaps();
  34498. if (defines["SHADOWFLOAT"] === undefined) {
  34499. needRebuild = true;
  34500. }
  34501. defines["SHADOWFLOAT"] = shadowEnabled &&
  34502. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34503. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34504. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34505. if (needRebuild) {
  34506. defines.rebuild();
  34507. }
  34508. return needNormals;
  34509. };
  34510. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34511. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34512. var uniformsList;
  34513. var uniformBuffersList = null;
  34514. if (uniformsListOrOptions.uniformsNames) {
  34515. var options = uniformsListOrOptions;
  34516. uniformsList = options.uniformsNames;
  34517. uniformBuffersList = options.uniformBuffersNames;
  34518. samplersList = options.samplers;
  34519. defines = options.defines;
  34520. maxSimultaneousLights = options.maxSimultaneousLights;
  34521. }
  34522. else {
  34523. uniformsList = uniformsListOrOptions;
  34524. if (!samplersList) {
  34525. samplersList = [];
  34526. }
  34527. }
  34528. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34529. if (!defines["LIGHT" + lightIndex]) {
  34530. break;
  34531. }
  34532. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34533. if (uniformBuffersList) {
  34534. uniformBuffersList.push("Light" + lightIndex);
  34535. }
  34536. samplersList.push("shadowSampler" + lightIndex);
  34537. }
  34538. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34539. uniformsList.push("morphTargetInfluences");
  34540. }
  34541. };
  34542. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34543. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34544. if (rank === void 0) { rank = 0; }
  34545. var lightFallbackRank = 0;
  34546. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34547. if (!defines["LIGHT" + lightIndex]) {
  34548. break;
  34549. }
  34550. if (lightIndex > 0) {
  34551. lightFallbackRank = rank + lightIndex;
  34552. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34553. }
  34554. if (!defines["SHADOWS"]) {
  34555. if (defines["SHADOW" + lightIndex]) {
  34556. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34557. }
  34558. if (defines["SHADOWPCF" + lightIndex]) {
  34559. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34560. }
  34561. if (defines["SHADOWESM" + lightIndex]) {
  34562. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34563. }
  34564. }
  34565. }
  34566. return lightFallbackRank++;
  34567. };
  34568. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34569. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34570. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34571. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34572. var manager = mesh.morphTargetManager;
  34573. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34574. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34575. for (var index = 0; index < influencers; index++) {
  34576. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34577. if (normal) {
  34578. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34579. }
  34580. if (tangent) {
  34581. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34582. }
  34583. if (attribs.length > maxAttributesCount) {
  34584. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34585. }
  34586. }
  34587. }
  34588. };
  34589. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34590. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34591. fallbacks.addCPUSkinningFallback(0, mesh);
  34592. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34593. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34594. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34595. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34596. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34597. }
  34598. }
  34599. };
  34600. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34601. if (defines["INSTANCES"]) {
  34602. attribs.push("world0");
  34603. attribs.push("world1");
  34604. attribs.push("world2");
  34605. attribs.push("world3");
  34606. }
  34607. };
  34608. // Bindings
  34609. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34610. if (light.shadowEnabled && mesh.receiveShadows) {
  34611. var shadowGenerator = light.getShadowGenerator();
  34612. if (shadowGenerator) {
  34613. shadowGenerator.bindShadowLight(lightIndex, effect);
  34614. }
  34615. }
  34616. };
  34617. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34618. light.transferToEffect(effect, lightIndex + "");
  34619. };
  34620. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34621. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34622. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34623. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34624. for (var i = 0; i < len; i++) {
  34625. var light = mesh._lightSources[i];
  34626. var iAsString = i.toString();
  34627. var scaledIntensity = light.getScaledIntensity();
  34628. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34629. MaterialHelper.BindLightProperties(light, effect, i);
  34630. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34631. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34632. if (defines["SPECULARTERM"]) {
  34633. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34634. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34635. }
  34636. // Shadows
  34637. if (scene.shadowsEnabled) {
  34638. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34639. }
  34640. light._uniformBuffer.update();
  34641. }
  34642. };
  34643. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34644. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34645. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34646. effect.setColor3("vFogColor", scene.fogColor);
  34647. }
  34648. };
  34649. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34650. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34651. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34652. if (matrices && effect) {
  34653. effect.setMatrices("mBones", matrices);
  34654. }
  34655. }
  34656. };
  34657. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34658. var manager = abstractMesh.morphTargetManager;
  34659. if (!abstractMesh || !manager) {
  34660. return;
  34661. }
  34662. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34663. };
  34664. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34665. if (defines["LOGARITHMICDEPTH"]) {
  34666. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34667. }
  34668. };
  34669. MaterialHelper.BindClipPlane = function (effect, scene) {
  34670. if (scene.clipPlane) {
  34671. var clipPlane = scene.clipPlane;
  34672. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34673. }
  34674. };
  34675. return MaterialHelper;
  34676. }());
  34677. BABYLON.MaterialHelper = MaterialHelper;
  34678. })(BABYLON || (BABYLON = {}));
  34679. //# sourceMappingURL=babylon.materialHelper.js.map
  34680. var BABYLON;
  34681. (function (BABYLON) {
  34682. var PushMaterial = /** @class */ (function (_super) {
  34683. __extends(PushMaterial, _super);
  34684. function PushMaterial(name, scene) {
  34685. var _this = _super.call(this, name, scene) || this;
  34686. _this.storeEffectOnSubMeshes = true;
  34687. return _this;
  34688. }
  34689. PushMaterial.prototype.getEffect = function () {
  34690. return this._activeEffect;
  34691. };
  34692. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34693. if (!mesh) {
  34694. return false;
  34695. }
  34696. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34697. return true;
  34698. }
  34699. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34700. };
  34701. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34702. this._activeEffect.setMatrix("world", world);
  34703. };
  34704. PushMaterial.prototype.bind = function (world, mesh) {
  34705. if (!mesh) {
  34706. return;
  34707. }
  34708. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34709. };
  34710. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34711. if (effect === void 0) { effect = null; }
  34712. _super.prototype._afterBind.call(this, mesh);
  34713. this.getScene()._cachedEffect = effect;
  34714. };
  34715. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34716. if (visibility === void 0) { visibility = 1; }
  34717. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34718. };
  34719. return PushMaterial;
  34720. }(BABYLON.Material));
  34721. BABYLON.PushMaterial = PushMaterial;
  34722. })(BABYLON || (BABYLON = {}));
  34723. //# sourceMappingURL=babylon.pushMaterial.js.map
  34724. var BABYLON;
  34725. (function (BABYLON) {
  34726. var StandardMaterialDefines = /** @class */ (function (_super) {
  34727. __extends(StandardMaterialDefines, _super);
  34728. function StandardMaterialDefines() {
  34729. var _this = _super.call(this) || this;
  34730. _this.MAINUV1 = false;
  34731. _this.MAINUV2 = false;
  34732. _this.DIFFUSE = false;
  34733. _this.DIFFUSEDIRECTUV = 0;
  34734. _this.AMBIENT = false;
  34735. _this.AMBIENTDIRECTUV = 0;
  34736. _this.OPACITY = false;
  34737. _this.OPACITYDIRECTUV = 0;
  34738. _this.OPACITYRGB = false;
  34739. _this.REFLECTION = false;
  34740. _this.EMISSIVE = false;
  34741. _this.EMISSIVEDIRECTUV = 0;
  34742. _this.SPECULAR = false;
  34743. _this.SPECULARDIRECTUV = 0;
  34744. _this.BUMP = false;
  34745. _this.BUMPDIRECTUV = 0;
  34746. _this.PARALLAX = false;
  34747. _this.PARALLAXOCCLUSION = false;
  34748. _this.SPECULAROVERALPHA = false;
  34749. _this.CLIPPLANE = false;
  34750. _this.ALPHATEST = false;
  34751. _this.DEPTHPREPASS = false;
  34752. _this.ALPHAFROMDIFFUSE = false;
  34753. _this.POINTSIZE = false;
  34754. _this.FOG = false;
  34755. _this.SPECULARTERM = false;
  34756. _this.DIFFUSEFRESNEL = false;
  34757. _this.OPACITYFRESNEL = false;
  34758. _this.REFLECTIONFRESNEL = false;
  34759. _this.REFRACTIONFRESNEL = false;
  34760. _this.EMISSIVEFRESNEL = false;
  34761. _this.FRESNEL = false;
  34762. _this.NORMAL = false;
  34763. _this.UV1 = false;
  34764. _this.UV2 = false;
  34765. _this.VERTEXCOLOR = false;
  34766. _this.VERTEXALPHA = false;
  34767. _this.NUM_BONE_INFLUENCERS = 0;
  34768. _this.BonesPerMesh = 0;
  34769. _this.INSTANCES = false;
  34770. _this.GLOSSINESS = false;
  34771. _this.ROUGHNESS = false;
  34772. _this.EMISSIVEASILLUMINATION = false;
  34773. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34774. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34775. _this.LIGHTMAP = false;
  34776. _this.LIGHTMAPDIRECTUV = 0;
  34777. _this.USELIGHTMAPASSHADOWMAP = false;
  34778. _this.REFLECTIONMAP_3D = false;
  34779. _this.REFLECTIONMAP_SPHERICAL = false;
  34780. _this.REFLECTIONMAP_PLANAR = false;
  34781. _this.REFLECTIONMAP_CUBIC = false;
  34782. _this.REFLECTIONMAP_PROJECTION = false;
  34783. _this.REFLECTIONMAP_SKYBOX = false;
  34784. _this.REFLECTIONMAP_EXPLICIT = false;
  34785. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34786. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34787. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34788. _this.INVERTCUBICMAP = false;
  34789. _this.LOGARITHMICDEPTH = false;
  34790. _this.REFRACTION = false;
  34791. _this.REFRACTIONMAP_3D = false;
  34792. _this.REFLECTIONOVERALPHA = false;
  34793. _this.TWOSIDEDLIGHTING = false;
  34794. _this.SHADOWFLOAT = false;
  34795. _this.MORPHTARGETS = false;
  34796. _this.MORPHTARGETS_NORMAL = false;
  34797. _this.MORPHTARGETS_TANGENT = false;
  34798. _this.NUM_MORPH_INFLUENCERS = 0;
  34799. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34800. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34801. _this.IMAGEPROCESSING = false;
  34802. _this.VIGNETTE = false;
  34803. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34804. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34805. _this.TONEMAPPING = false;
  34806. _this.CONTRAST = false;
  34807. _this.COLORCURVES = false;
  34808. _this.COLORGRADING = false;
  34809. _this.COLORGRADING3D = false;
  34810. _this.SAMPLER3DGREENDEPTH = false;
  34811. _this.SAMPLER3DBGRMAP = false;
  34812. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34813. _this.EXPOSURE = false;
  34814. _this.rebuild();
  34815. return _this;
  34816. }
  34817. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34818. var modes = [
  34819. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34820. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34821. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34822. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34823. ];
  34824. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34825. var mode = modes_1[_i];
  34826. this[mode] = (mode === modeToEnable);
  34827. }
  34828. };
  34829. return StandardMaterialDefines;
  34830. }(BABYLON.MaterialDefines));
  34831. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34832. var StandardMaterial = /** @class */ (function (_super) {
  34833. __extends(StandardMaterial, _super);
  34834. function StandardMaterial(name, scene) {
  34835. var _this = _super.call(this, name, scene) || this;
  34836. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34837. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34838. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34839. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34840. _this.specularPower = 64;
  34841. _this._useAlphaFromDiffuseTexture = false;
  34842. _this._useEmissiveAsIllumination = false;
  34843. _this._linkEmissiveWithDiffuse = false;
  34844. _this._useSpecularOverAlpha = false;
  34845. _this._useReflectionOverAlpha = false;
  34846. _this._disableLighting = false;
  34847. _this._useParallax = false;
  34848. _this._useParallaxOcclusion = false;
  34849. _this.parallaxScaleBias = 0.05;
  34850. _this._roughness = 0;
  34851. _this.indexOfRefraction = 0.98;
  34852. _this.invertRefractionY = true;
  34853. _this._useLightmapAsShadowmap = false;
  34854. _this._useReflectionFresnelFromSpecular = false;
  34855. _this._useGlossinessFromSpecularMapAlpha = false;
  34856. _this._maxSimultaneousLights = 4;
  34857. /**
  34858. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34859. */
  34860. _this._invertNormalMapX = false;
  34861. /**
  34862. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34863. */
  34864. _this._invertNormalMapY = false;
  34865. /**
  34866. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34867. */
  34868. _this._twoSidedLighting = false;
  34869. _this._renderTargets = new BABYLON.SmartArray(16);
  34870. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34871. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34872. // Setup the default processing configuration to the scene.
  34873. _this._attachImageProcessingConfiguration(null);
  34874. _this.getRenderTargetTextures = function () {
  34875. _this._renderTargets.reset();
  34876. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34877. _this._renderTargets.push(_this._reflectionTexture);
  34878. }
  34879. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34880. _this._renderTargets.push(_this._refractionTexture);
  34881. }
  34882. return _this._renderTargets;
  34883. };
  34884. return _this;
  34885. }
  34886. ;
  34887. ;
  34888. ;
  34889. ;
  34890. ;
  34891. ;
  34892. ;
  34893. ;
  34894. ;
  34895. ;
  34896. ;
  34897. ;
  34898. ;
  34899. ;
  34900. ;
  34901. ;
  34902. ;
  34903. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34904. /**
  34905. * Gets the image processing configuration used either in this material.
  34906. */
  34907. get: function () {
  34908. return this._imageProcessingConfiguration;
  34909. },
  34910. /**
  34911. * Sets the Default image processing configuration used either in the this material.
  34912. *
  34913. * If sets to null, the scene one is in use.
  34914. */
  34915. set: function (value) {
  34916. this._attachImageProcessingConfiguration(value);
  34917. // Ensure the effect will be rebuilt.
  34918. this._markAllSubMeshesAsTexturesDirty();
  34919. },
  34920. enumerable: true,
  34921. configurable: true
  34922. });
  34923. /**
  34924. * Attaches a new image processing configuration to the Standard Material.
  34925. * @param configuration
  34926. */
  34927. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34928. var _this = this;
  34929. if (configuration === this._imageProcessingConfiguration) {
  34930. return;
  34931. }
  34932. // Detaches observer.
  34933. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34934. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34935. }
  34936. // Pick the scene configuration if needed.
  34937. if (!configuration) {
  34938. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34939. }
  34940. else {
  34941. this._imageProcessingConfiguration = configuration;
  34942. }
  34943. // Attaches observer.
  34944. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34945. _this._markAllSubMeshesAsImageProcessingDirty();
  34946. });
  34947. };
  34948. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34949. /**
  34950. * Gets wether the color curves effect is enabled.
  34951. */
  34952. get: function () {
  34953. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34954. },
  34955. /**
  34956. * Sets wether the color curves effect is enabled.
  34957. */
  34958. set: function (value) {
  34959. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34965. /**
  34966. * Gets wether the color grading effect is enabled.
  34967. */
  34968. get: function () {
  34969. return this.imageProcessingConfiguration.colorGradingEnabled;
  34970. },
  34971. /**
  34972. * Gets wether the color grading effect is enabled.
  34973. */
  34974. set: function (value) {
  34975. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34976. },
  34977. enumerable: true,
  34978. configurable: true
  34979. });
  34980. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34981. /**
  34982. * Gets wether tonemapping is enabled or not.
  34983. */
  34984. get: function () {
  34985. return this._imageProcessingConfiguration.toneMappingEnabled;
  34986. },
  34987. /**
  34988. * Sets wether tonemapping is enabled or not
  34989. */
  34990. set: function (value) {
  34991. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34992. },
  34993. enumerable: true,
  34994. configurable: true
  34995. });
  34996. ;
  34997. ;
  34998. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34999. /**
  35000. * The camera exposure used on this material.
  35001. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35002. * This corresponds to a photographic exposure.
  35003. */
  35004. get: function () {
  35005. return this._imageProcessingConfiguration.exposure;
  35006. },
  35007. /**
  35008. * The camera exposure used on this material.
  35009. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35010. * This corresponds to a photographic exposure.
  35011. */
  35012. set: function (value) {
  35013. this._imageProcessingConfiguration.exposure = value;
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. ;
  35019. ;
  35020. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35021. /**
  35022. * Gets The camera contrast used on this material.
  35023. */
  35024. get: function () {
  35025. return this._imageProcessingConfiguration.contrast;
  35026. },
  35027. /**
  35028. * Sets The camera contrast used on this material.
  35029. */
  35030. set: function (value) {
  35031. this._imageProcessingConfiguration.contrast = value;
  35032. },
  35033. enumerable: true,
  35034. configurable: true
  35035. });
  35036. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35037. /**
  35038. * Gets the Color Grading 2D Lookup Texture.
  35039. */
  35040. get: function () {
  35041. return this._imageProcessingConfiguration.colorGradingTexture;
  35042. },
  35043. /**
  35044. * Sets the Color Grading 2D Lookup Texture.
  35045. */
  35046. set: function (value) {
  35047. this._imageProcessingConfiguration.colorGradingTexture = value;
  35048. },
  35049. enumerable: true,
  35050. configurable: true
  35051. });
  35052. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35053. /**
  35054. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35055. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35056. * 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;
  35057. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35058. */
  35059. get: function () {
  35060. return this._imageProcessingConfiguration.colorCurves;
  35061. },
  35062. /**
  35063. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35064. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35065. * 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;
  35066. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35067. */
  35068. set: function (value) {
  35069. this._imageProcessingConfiguration.colorCurves = value;
  35070. },
  35071. enumerable: true,
  35072. configurable: true
  35073. });
  35074. StandardMaterial.prototype.getClassName = function () {
  35075. return "StandardMaterial";
  35076. };
  35077. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35078. get: function () {
  35079. return this._useLogarithmicDepth;
  35080. },
  35081. set: function (value) {
  35082. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35083. this._markAllSubMeshesAsMiscDirty();
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. StandardMaterial.prototype.needAlphaBlending = function () {
  35089. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35090. };
  35091. StandardMaterial.prototype.needAlphaTesting = function () {
  35092. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35093. };
  35094. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35095. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35096. };
  35097. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35098. return this._diffuseTexture;
  35099. };
  35100. /**
  35101. * Child classes can use it to update shaders
  35102. */
  35103. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35104. if (useInstances === void 0) { useInstances = false; }
  35105. if (subMesh.effect && this.isFrozen) {
  35106. if (this._wasPreviouslyReady && subMesh.effect) {
  35107. return true;
  35108. }
  35109. }
  35110. if (!subMesh._materialDefines) {
  35111. subMesh._materialDefines = new StandardMaterialDefines();
  35112. }
  35113. var scene = this.getScene();
  35114. var defines = subMesh._materialDefines;
  35115. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35116. if (defines._renderId === scene.getRenderId()) {
  35117. return true;
  35118. }
  35119. }
  35120. var engine = scene.getEngine();
  35121. // Lights
  35122. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35123. // Textures
  35124. if (defines._areTexturesDirty) {
  35125. defines._needUVs = false;
  35126. defines.MAINUV1 = false;
  35127. defines.MAINUV2 = false;
  35128. if (scene.texturesEnabled) {
  35129. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35130. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35131. return false;
  35132. }
  35133. else {
  35134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35135. }
  35136. }
  35137. else {
  35138. defines.DIFFUSE = false;
  35139. }
  35140. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35141. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35142. return false;
  35143. }
  35144. else {
  35145. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35146. }
  35147. }
  35148. else {
  35149. defines.AMBIENT = false;
  35150. }
  35151. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35152. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35153. return false;
  35154. }
  35155. else {
  35156. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35157. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35158. }
  35159. }
  35160. else {
  35161. defines.OPACITY = false;
  35162. }
  35163. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35164. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35165. return false;
  35166. }
  35167. else {
  35168. defines._needNormals = true;
  35169. defines.REFLECTION = true;
  35170. defines.ROUGHNESS = (this._roughness > 0);
  35171. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35172. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35173. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35174. switch (this._reflectionTexture.coordinatesMode) {
  35175. case BABYLON.Texture.CUBIC_MODE:
  35176. case BABYLON.Texture.INVCUBIC_MODE:
  35177. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35178. break;
  35179. case BABYLON.Texture.EXPLICIT_MODE:
  35180. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35181. break;
  35182. case BABYLON.Texture.PLANAR_MODE:
  35183. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35184. break;
  35185. case BABYLON.Texture.PROJECTION_MODE:
  35186. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35187. break;
  35188. case BABYLON.Texture.SKYBOX_MODE:
  35189. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35190. break;
  35191. case BABYLON.Texture.SPHERICAL_MODE:
  35192. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35193. break;
  35194. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35195. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35196. break;
  35197. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35198. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35199. break;
  35200. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35201. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35202. break;
  35203. }
  35204. }
  35205. }
  35206. else {
  35207. defines.REFLECTION = false;
  35208. }
  35209. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35210. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35211. return false;
  35212. }
  35213. else {
  35214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35215. }
  35216. }
  35217. else {
  35218. defines.EMISSIVE = false;
  35219. }
  35220. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35221. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35222. return false;
  35223. }
  35224. else {
  35225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35226. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35227. }
  35228. }
  35229. else {
  35230. defines.LIGHTMAP = false;
  35231. }
  35232. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35233. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35234. return false;
  35235. }
  35236. else {
  35237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35238. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35239. }
  35240. }
  35241. else {
  35242. defines.SPECULAR = false;
  35243. }
  35244. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35245. // Bump texure can not be not blocking.
  35246. if (!this._bumpTexture.isReady()) {
  35247. return false;
  35248. }
  35249. else {
  35250. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35251. defines.PARALLAX = this._useParallax;
  35252. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35253. }
  35254. }
  35255. else {
  35256. defines.BUMP = false;
  35257. }
  35258. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35259. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35260. return false;
  35261. }
  35262. else {
  35263. defines._needUVs = true;
  35264. defines.REFRACTION = true;
  35265. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35266. }
  35267. }
  35268. else {
  35269. defines.REFRACTION = false;
  35270. }
  35271. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35272. }
  35273. else {
  35274. defines.DIFFUSE = false;
  35275. defines.AMBIENT = false;
  35276. defines.OPACITY = false;
  35277. defines.REFLECTION = false;
  35278. defines.EMISSIVE = false;
  35279. defines.LIGHTMAP = false;
  35280. defines.BUMP = false;
  35281. defines.REFRACTION = false;
  35282. }
  35283. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35284. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35285. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35286. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35287. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35288. }
  35289. if (defines._areImageProcessingDirty) {
  35290. if (!this._imageProcessingConfiguration.isReady()) {
  35291. return false;
  35292. }
  35293. this._imageProcessingConfiguration.prepareDefines(defines);
  35294. }
  35295. if (defines._areFresnelDirty) {
  35296. if (StandardMaterial.FresnelEnabled) {
  35297. // Fresnel
  35298. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35299. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35300. this._reflectionFresnelParameters) {
  35301. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35302. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35303. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35304. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35305. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35306. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35307. defines._needNormals = true;
  35308. defines.FRESNEL = true;
  35309. }
  35310. }
  35311. else {
  35312. defines.FRESNEL = false;
  35313. }
  35314. }
  35315. // Misc.
  35316. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35317. // Attribs
  35318. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35319. // Values that need to be evaluated on every frame
  35320. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35321. // Get correct effect
  35322. if (defines.isDirty) {
  35323. defines.markAsProcessed();
  35324. scene.resetCachedMaterial();
  35325. // Fallbacks
  35326. var fallbacks = new BABYLON.EffectFallbacks();
  35327. if (defines.REFLECTION) {
  35328. fallbacks.addFallback(0, "REFLECTION");
  35329. }
  35330. if (defines.SPECULAR) {
  35331. fallbacks.addFallback(0, "SPECULAR");
  35332. }
  35333. if (defines.BUMP) {
  35334. fallbacks.addFallback(0, "BUMP");
  35335. }
  35336. if (defines.PARALLAX) {
  35337. fallbacks.addFallback(1, "PARALLAX");
  35338. }
  35339. if (defines.PARALLAXOCCLUSION) {
  35340. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35341. }
  35342. if (defines.SPECULAROVERALPHA) {
  35343. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35344. }
  35345. if (defines.FOG) {
  35346. fallbacks.addFallback(1, "FOG");
  35347. }
  35348. if (defines.POINTSIZE) {
  35349. fallbacks.addFallback(0, "POINTSIZE");
  35350. }
  35351. if (defines.LOGARITHMICDEPTH) {
  35352. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35353. }
  35354. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35355. if (defines.SPECULARTERM) {
  35356. fallbacks.addFallback(0, "SPECULARTERM");
  35357. }
  35358. if (defines.DIFFUSEFRESNEL) {
  35359. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35360. }
  35361. if (defines.OPACITYFRESNEL) {
  35362. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35363. }
  35364. if (defines.REFLECTIONFRESNEL) {
  35365. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35366. }
  35367. if (defines.EMISSIVEFRESNEL) {
  35368. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35369. }
  35370. if (defines.FRESNEL) {
  35371. fallbacks.addFallback(4, "FRESNEL");
  35372. }
  35373. //Attributes
  35374. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35375. if (defines.NORMAL) {
  35376. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35377. }
  35378. if (defines.UV1) {
  35379. attribs.push(BABYLON.VertexBuffer.UVKind);
  35380. }
  35381. if (defines.UV2) {
  35382. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35383. }
  35384. if (defines.VERTEXCOLOR) {
  35385. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35386. }
  35387. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35388. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35389. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35390. var shaderName = "default";
  35391. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35392. "vFogInfos", "vFogColor", "pointSize",
  35393. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35394. "mBones",
  35395. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35396. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35397. "logarithmicDepthConstant", "vTangentSpaceParams"
  35398. ];
  35399. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35400. var uniformBuffers = ["Material", "Scene"];
  35401. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35402. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35403. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35404. uniformsNames: uniforms,
  35405. uniformBuffersNames: uniformBuffers,
  35406. samplers: samplers,
  35407. defines: defines,
  35408. maxSimultaneousLights: this._maxSimultaneousLights
  35409. });
  35410. if (this.customShaderNameResolve) {
  35411. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35412. }
  35413. var join = defines.toString();
  35414. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35415. attributes: attribs,
  35416. uniformsNames: uniforms,
  35417. uniformBuffersNames: uniformBuffers,
  35418. samplers: samplers,
  35419. defines: join,
  35420. fallbacks: fallbacks,
  35421. onCompiled: this.onCompiled,
  35422. onError: this.onError,
  35423. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35424. }, engine), defines);
  35425. this.buildUniformLayout();
  35426. }
  35427. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35428. return false;
  35429. }
  35430. defines._renderId = scene.getRenderId();
  35431. this._wasPreviouslyReady = true;
  35432. return true;
  35433. };
  35434. StandardMaterial.prototype.buildUniformLayout = function () {
  35435. // Order is important !
  35436. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35437. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35438. this._uniformBuffer.addUniform("opacityParts", 4);
  35439. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35440. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35441. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35442. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35443. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35444. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35445. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35446. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35447. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35448. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35449. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35450. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35451. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35452. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35453. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35454. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35455. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35456. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35457. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35458. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35459. this._uniformBuffer.addUniform("specularMatrix", 16);
  35460. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35461. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35462. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35463. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35464. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35465. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35466. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35467. this._uniformBuffer.addUniform("pointSize", 1);
  35468. this._uniformBuffer.create();
  35469. };
  35470. StandardMaterial.prototype.unbind = function () {
  35471. if (this._activeEffect) {
  35472. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35473. this._activeEffect.setTexture("reflection2DSampler", null);
  35474. }
  35475. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35476. this._activeEffect.setTexture("refraction2DSampler", null);
  35477. }
  35478. }
  35479. _super.prototype.unbind.call(this);
  35480. };
  35481. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35482. var scene = this.getScene();
  35483. var defines = subMesh._materialDefines;
  35484. if (!defines) {
  35485. return;
  35486. }
  35487. var effect = subMesh.effect;
  35488. if (!effect) {
  35489. return;
  35490. }
  35491. this._activeEffect = effect;
  35492. // Matrices
  35493. this.bindOnlyWorldMatrix(world);
  35494. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35495. // Bones
  35496. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35497. if (mustRebind) {
  35498. this._uniformBuffer.bindToEffect(effect, "Material");
  35499. this.bindViewProjection(effect);
  35500. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35501. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35502. // Fresnel
  35503. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35504. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35505. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35506. }
  35507. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35508. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35509. }
  35510. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35511. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35512. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35513. }
  35514. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35515. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35516. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35517. }
  35518. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35519. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35520. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35521. }
  35522. }
  35523. // Textures
  35524. if (scene.texturesEnabled) {
  35525. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35526. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35527. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35528. }
  35529. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35530. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35531. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35532. }
  35533. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35534. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35535. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35536. }
  35537. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35538. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35539. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35540. }
  35541. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35542. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35543. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35544. }
  35545. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35546. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35547. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35548. }
  35549. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35550. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35551. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35552. }
  35553. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35554. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35555. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35556. if (scene._mirroredCameraPosition) {
  35557. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35558. }
  35559. else {
  35560. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35561. }
  35562. }
  35563. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35564. var depth = 1.0;
  35565. if (!this._refractionTexture.isCube) {
  35566. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35567. if (this._refractionTexture.depth) {
  35568. depth = this._refractionTexture.depth;
  35569. }
  35570. }
  35571. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35572. }
  35573. }
  35574. // Point size
  35575. if (this.pointsCloud) {
  35576. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35577. }
  35578. if (defines.SPECULARTERM) {
  35579. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35580. }
  35581. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35582. // Diffuse
  35583. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35584. }
  35585. // Textures
  35586. if (scene.texturesEnabled) {
  35587. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35588. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35589. }
  35590. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35591. effect.setTexture("ambientSampler", this._ambientTexture);
  35592. }
  35593. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35594. effect.setTexture("opacitySampler", this._opacityTexture);
  35595. }
  35596. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35597. if (this._reflectionTexture.isCube) {
  35598. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35599. }
  35600. else {
  35601. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35602. }
  35603. }
  35604. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35605. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35606. }
  35607. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35608. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35609. }
  35610. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35611. effect.setTexture("specularSampler", this._specularTexture);
  35612. }
  35613. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35614. effect.setTexture("bumpSampler", this._bumpTexture);
  35615. }
  35616. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35617. var depth = 1.0;
  35618. if (this._refractionTexture.isCube) {
  35619. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35620. }
  35621. else {
  35622. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35623. }
  35624. }
  35625. }
  35626. // Clip plane
  35627. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35628. // Colors
  35629. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35630. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35631. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35632. }
  35633. if (mustRebind || !this.isFrozen) {
  35634. // Lights
  35635. if (scene.lightsEnabled && !this._disableLighting) {
  35636. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35637. }
  35638. // View
  35639. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35640. this.bindView(effect);
  35641. }
  35642. // Fog
  35643. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35644. // Morph targets
  35645. if (defines.NUM_MORPH_INFLUENCERS) {
  35646. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35647. }
  35648. // Log. depth
  35649. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35650. // image processing
  35651. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35652. this._imageProcessingConfiguration.bind(this._activeEffect);
  35653. }
  35654. }
  35655. this._uniformBuffer.update();
  35656. this._afterBind(mesh, this._activeEffect);
  35657. };
  35658. StandardMaterial.prototype.getAnimatables = function () {
  35659. var results = [];
  35660. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35661. results.push(this._diffuseTexture);
  35662. }
  35663. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35664. results.push(this._ambientTexture);
  35665. }
  35666. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35667. results.push(this._opacityTexture);
  35668. }
  35669. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35670. results.push(this._reflectionTexture);
  35671. }
  35672. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35673. results.push(this._emissiveTexture);
  35674. }
  35675. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35676. results.push(this._specularTexture);
  35677. }
  35678. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35679. results.push(this._bumpTexture);
  35680. }
  35681. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35682. results.push(this._lightmapTexture);
  35683. }
  35684. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35685. results.push(this._refractionTexture);
  35686. }
  35687. return results;
  35688. };
  35689. StandardMaterial.prototype.getActiveTextures = function () {
  35690. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35691. if (this._diffuseTexture) {
  35692. activeTextures.push(this._diffuseTexture);
  35693. }
  35694. if (this._ambientTexture) {
  35695. activeTextures.push(this._ambientTexture);
  35696. }
  35697. if (this._opacityTexture) {
  35698. activeTextures.push(this._opacityTexture);
  35699. }
  35700. if (this._reflectionTexture) {
  35701. activeTextures.push(this._reflectionTexture);
  35702. }
  35703. if (this._emissiveTexture) {
  35704. activeTextures.push(this._emissiveTexture);
  35705. }
  35706. if (this._specularTexture) {
  35707. activeTextures.push(this._specularTexture);
  35708. }
  35709. if (this._bumpTexture) {
  35710. activeTextures.push(this._bumpTexture);
  35711. }
  35712. if (this._lightmapTexture) {
  35713. activeTextures.push(this._lightmapTexture);
  35714. }
  35715. if (this._refractionTexture) {
  35716. activeTextures.push(this._refractionTexture);
  35717. }
  35718. return activeTextures;
  35719. };
  35720. StandardMaterial.prototype.hasTexture = function (texture) {
  35721. if (_super.prototype.hasTexture.call(this, texture)) {
  35722. return true;
  35723. }
  35724. if (this._diffuseTexture === texture) {
  35725. return true;
  35726. }
  35727. if (this._ambientTexture === texture) {
  35728. return true;
  35729. }
  35730. if (this._opacityTexture === texture) {
  35731. return true;
  35732. }
  35733. if (this._reflectionTexture === texture) {
  35734. return true;
  35735. }
  35736. if (this._emissiveTexture === texture) {
  35737. return true;
  35738. }
  35739. if (this._specularTexture === texture) {
  35740. return true;
  35741. }
  35742. if (this._bumpTexture === texture) {
  35743. return true;
  35744. }
  35745. if (this._lightmapTexture === texture) {
  35746. return true;
  35747. }
  35748. if (this._refractionTexture === texture) {
  35749. return true;
  35750. }
  35751. return false;
  35752. };
  35753. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35754. if (forceDisposeTextures) {
  35755. if (this._diffuseTexture) {
  35756. this._diffuseTexture.dispose();
  35757. }
  35758. if (this._ambientTexture) {
  35759. this._ambientTexture.dispose();
  35760. }
  35761. if (this._opacityTexture) {
  35762. this._opacityTexture.dispose();
  35763. }
  35764. if (this._reflectionTexture) {
  35765. this._reflectionTexture.dispose();
  35766. }
  35767. if (this._emissiveTexture) {
  35768. this._emissiveTexture.dispose();
  35769. }
  35770. if (this._specularTexture) {
  35771. this._specularTexture.dispose();
  35772. }
  35773. if (this._bumpTexture) {
  35774. this._bumpTexture.dispose();
  35775. }
  35776. if (this._lightmapTexture) {
  35777. this._lightmapTexture.dispose();
  35778. }
  35779. if (this._refractionTexture) {
  35780. this._refractionTexture.dispose();
  35781. }
  35782. }
  35783. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35784. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35785. }
  35786. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35787. };
  35788. StandardMaterial.prototype.clone = function (name) {
  35789. var _this = this;
  35790. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35791. result.name = name;
  35792. result.id = name;
  35793. return result;
  35794. };
  35795. StandardMaterial.prototype.serialize = function () {
  35796. return BABYLON.SerializationHelper.Serialize(this);
  35797. };
  35798. // Statics
  35799. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35800. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35801. };
  35802. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35803. get: function () {
  35804. return StandardMaterial._DiffuseTextureEnabled;
  35805. },
  35806. set: function (value) {
  35807. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35808. return;
  35809. }
  35810. StandardMaterial._DiffuseTextureEnabled = value;
  35811. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35817. get: function () {
  35818. return StandardMaterial._AmbientTextureEnabled;
  35819. },
  35820. set: function (value) {
  35821. if (StandardMaterial._AmbientTextureEnabled === value) {
  35822. return;
  35823. }
  35824. StandardMaterial._AmbientTextureEnabled = value;
  35825. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35826. },
  35827. enumerable: true,
  35828. configurable: true
  35829. });
  35830. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35831. get: function () {
  35832. return StandardMaterial._OpacityTextureEnabled;
  35833. },
  35834. set: function (value) {
  35835. if (StandardMaterial._OpacityTextureEnabled === value) {
  35836. return;
  35837. }
  35838. StandardMaterial._OpacityTextureEnabled = value;
  35839. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35840. },
  35841. enumerable: true,
  35842. configurable: true
  35843. });
  35844. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35845. get: function () {
  35846. return StandardMaterial._ReflectionTextureEnabled;
  35847. },
  35848. set: function (value) {
  35849. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35850. return;
  35851. }
  35852. StandardMaterial._ReflectionTextureEnabled = value;
  35853. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35854. },
  35855. enumerable: true,
  35856. configurable: true
  35857. });
  35858. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35859. get: function () {
  35860. return StandardMaterial._EmissiveTextureEnabled;
  35861. },
  35862. set: function (value) {
  35863. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35864. return;
  35865. }
  35866. StandardMaterial._EmissiveTextureEnabled = value;
  35867. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35868. },
  35869. enumerable: true,
  35870. configurable: true
  35871. });
  35872. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35873. get: function () {
  35874. return StandardMaterial._SpecularTextureEnabled;
  35875. },
  35876. set: function (value) {
  35877. if (StandardMaterial._SpecularTextureEnabled === value) {
  35878. return;
  35879. }
  35880. StandardMaterial._SpecularTextureEnabled = value;
  35881. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35882. },
  35883. enumerable: true,
  35884. configurable: true
  35885. });
  35886. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35887. get: function () {
  35888. return StandardMaterial._BumpTextureEnabled;
  35889. },
  35890. set: function (value) {
  35891. if (StandardMaterial._BumpTextureEnabled === value) {
  35892. return;
  35893. }
  35894. StandardMaterial._BumpTextureEnabled = value;
  35895. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35896. },
  35897. enumerable: true,
  35898. configurable: true
  35899. });
  35900. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35901. get: function () {
  35902. return StandardMaterial._LightmapTextureEnabled;
  35903. },
  35904. set: function (value) {
  35905. if (StandardMaterial._LightmapTextureEnabled === value) {
  35906. return;
  35907. }
  35908. StandardMaterial._LightmapTextureEnabled = value;
  35909. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35910. },
  35911. enumerable: true,
  35912. configurable: true
  35913. });
  35914. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35915. get: function () {
  35916. return StandardMaterial._RefractionTextureEnabled;
  35917. },
  35918. set: function (value) {
  35919. if (StandardMaterial._RefractionTextureEnabled === value) {
  35920. return;
  35921. }
  35922. StandardMaterial._RefractionTextureEnabled = value;
  35923. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35924. },
  35925. enumerable: true,
  35926. configurable: true
  35927. });
  35928. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35929. get: function () {
  35930. return StandardMaterial._ColorGradingTextureEnabled;
  35931. },
  35932. set: function (value) {
  35933. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35934. return;
  35935. }
  35936. StandardMaterial._ColorGradingTextureEnabled = value;
  35937. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35938. },
  35939. enumerable: true,
  35940. configurable: true
  35941. });
  35942. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35943. get: function () {
  35944. return StandardMaterial._FresnelEnabled;
  35945. },
  35946. set: function (value) {
  35947. if (StandardMaterial._FresnelEnabled === value) {
  35948. return;
  35949. }
  35950. StandardMaterial._FresnelEnabled = value;
  35951. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35952. },
  35953. enumerable: true,
  35954. configurable: true
  35955. });
  35956. // Flags used to enable or disable a type of texture for all Standard Materials
  35957. StandardMaterial._DiffuseTextureEnabled = true;
  35958. StandardMaterial._AmbientTextureEnabled = true;
  35959. StandardMaterial._OpacityTextureEnabled = true;
  35960. StandardMaterial._ReflectionTextureEnabled = true;
  35961. StandardMaterial._EmissiveTextureEnabled = true;
  35962. StandardMaterial._SpecularTextureEnabled = true;
  35963. StandardMaterial._BumpTextureEnabled = true;
  35964. StandardMaterial._LightmapTextureEnabled = true;
  35965. StandardMaterial._RefractionTextureEnabled = true;
  35966. StandardMaterial._ColorGradingTextureEnabled = true;
  35967. StandardMaterial._FresnelEnabled = true;
  35968. __decorate([
  35969. BABYLON.serializeAsTexture("diffuseTexture")
  35970. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35971. __decorate([
  35972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35973. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35974. __decorate([
  35975. BABYLON.serializeAsTexture("ambientTexture")
  35976. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35977. __decorate([
  35978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35979. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35980. __decorate([
  35981. BABYLON.serializeAsTexture("opacityTexture")
  35982. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35983. __decorate([
  35984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35985. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35986. __decorate([
  35987. BABYLON.serializeAsTexture("reflectionTexture")
  35988. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35989. __decorate([
  35990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35991. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35992. __decorate([
  35993. BABYLON.serializeAsTexture("emissiveTexture")
  35994. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35995. __decorate([
  35996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35997. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35998. __decorate([
  35999. BABYLON.serializeAsTexture("specularTexture")
  36000. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36001. __decorate([
  36002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36003. ], StandardMaterial.prototype, "specularTexture", void 0);
  36004. __decorate([
  36005. BABYLON.serializeAsTexture("bumpTexture")
  36006. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36007. __decorate([
  36008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36009. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36010. __decorate([
  36011. BABYLON.serializeAsTexture("lightmapTexture")
  36012. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36013. __decorate([
  36014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36015. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36016. __decorate([
  36017. BABYLON.serializeAsTexture("refractionTexture")
  36018. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36019. __decorate([
  36020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36021. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36022. __decorate([
  36023. BABYLON.serializeAsColor3("ambient")
  36024. ], StandardMaterial.prototype, "ambientColor", void 0);
  36025. __decorate([
  36026. BABYLON.serializeAsColor3("diffuse")
  36027. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36028. __decorate([
  36029. BABYLON.serializeAsColor3("specular")
  36030. ], StandardMaterial.prototype, "specularColor", void 0);
  36031. __decorate([
  36032. BABYLON.serializeAsColor3("emissive")
  36033. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36034. __decorate([
  36035. BABYLON.serialize()
  36036. ], StandardMaterial.prototype, "specularPower", void 0);
  36037. __decorate([
  36038. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36039. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36040. __decorate([
  36041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36042. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36043. __decorate([
  36044. BABYLON.serialize("useEmissiveAsIllumination")
  36045. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36046. __decorate([
  36047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36048. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36049. __decorate([
  36050. BABYLON.serialize("linkEmissiveWithDiffuse")
  36051. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36052. __decorate([
  36053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36054. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36055. __decorate([
  36056. BABYLON.serialize("useSpecularOverAlpha")
  36057. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36058. __decorate([
  36059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36060. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36061. __decorate([
  36062. BABYLON.serialize("useReflectionOverAlpha")
  36063. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36064. __decorate([
  36065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36066. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36067. __decorate([
  36068. BABYLON.serialize("disableLighting")
  36069. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36070. __decorate([
  36071. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36072. ], StandardMaterial.prototype, "disableLighting", void 0);
  36073. __decorate([
  36074. BABYLON.serialize("useParallax")
  36075. ], StandardMaterial.prototype, "_useParallax", void 0);
  36076. __decorate([
  36077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36078. ], StandardMaterial.prototype, "useParallax", void 0);
  36079. __decorate([
  36080. BABYLON.serialize("useParallaxOcclusion")
  36081. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36082. __decorate([
  36083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36084. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36085. __decorate([
  36086. BABYLON.serialize()
  36087. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36088. __decorate([
  36089. BABYLON.serialize("roughness")
  36090. ], StandardMaterial.prototype, "_roughness", void 0);
  36091. __decorate([
  36092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36093. ], StandardMaterial.prototype, "roughness", void 0);
  36094. __decorate([
  36095. BABYLON.serialize()
  36096. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36097. __decorate([
  36098. BABYLON.serialize()
  36099. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36100. __decorate([
  36101. BABYLON.serialize("useLightmapAsShadowmap")
  36102. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36103. __decorate([
  36104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36105. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36106. __decorate([
  36107. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36108. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36109. __decorate([
  36110. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36111. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36112. __decorate([
  36113. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36114. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36115. __decorate([
  36116. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36117. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36118. __decorate([
  36119. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36120. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36121. __decorate([
  36122. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36123. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36124. __decorate([
  36125. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36126. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36127. __decorate([
  36128. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36129. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36130. __decorate([
  36131. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36132. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36133. __decorate([
  36134. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36135. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36136. __decorate([
  36137. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36138. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36139. __decorate([
  36140. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36141. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36142. __decorate([
  36143. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36144. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36145. __decorate([
  36146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36147. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36148. __decorate([
  36149. BABYLON.serialize("maxSimultaneousLights")
  36150. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36151. __decorate([
  36152. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36153. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36154. __decorate([
  36155. BABYLON.serialize("invertNormalMapX")
  36156. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36157. __decorate([
  36158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36159. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36160. __decorate([
  36161. BABYLON.serialize("invertNormalMapY")
  36162. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36163. __decorate([
  36164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36165. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36166. __decorate([
  36167. BABYLON.serialize("twoSidedLighting")
  36168. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36169. __decorate([
  36170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36171. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36172. __decorate([
  36173. BABYLON.serialize()
  36174. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36175. return StandardMaterial;
  36176. }(BABYLON.PushMaterial));
  36177. BABYLON.StandardMaterial = StandardMaterial;
  36178. })(BABYLON || (BABYLON = {}));
  36179. //# sourceMappingURL=babylon.standardMaterial.js.map
  36180. var BABYLON;
  36181. (function (BABYLON) {
  36182. var PBRMaterialDefines = /** @class */ (function (_super) {
  36183. __extends(PBRMaterialDefines, _super);
  36184. function PBRMaterialDefines() {
  36185. var _this = _super.call(this) || this;
  36186. _this.PBR = true;
  36187. _this.MAINUV1 = false;
  36188. _this.MAINUV2 = false;
  36189. _this.UV1 = false;
  36190. _this.UV2 = false;
  36191. _this.ALBEDO = false;
  36192. _this.ALBEDODIRECTUV = 0;
  36193. _this.VERTEXCOLOR = false;
  36194. _this.AMBIENT = false;
  36195. _this.AMBIENTDIRECTUV = 0;
  36196. _this.AMBIENTINGRAYSCALE = false;
  36197. _this.OPACITY = false;
  36198. _this.VERTEXALPHA = false;
  36199. _this.OPACITYDIRECTUV = 0;
  36200. _this.OPACITYRGB = false;
  36201. _this.ALPHATEST = false;
  36202. _this.DEPTHPREPASS = false;
  36203. _this.ALPHABLEND = false;
  36204. _this.ALPHAFROMALBEDO = false;
  36205. _this.ALPHATESTVALUE = 0.5;
  36206. _this.SPECULAROVERALPHA = false;
  36207. _this.RADIANCEOVERALPHA = false;
  36208. _this.ALPHAFRESNEL = false;
  36209. _this.LINEARALPHAFRESNEL = false;
  36210. _this.PREMULTIPLYALPHA = false;
  36211. _this.EMISSIVE = false;
  36212. _this.EMISSIVEDIRECTUV = 0;
  36213. _this.REFLECTIVITY = false;
  36214. _this.REFLECTIVITYDIRECTUV = 0;
  36215. _this.SPECULARTERM = false;
  36216. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36217. _this.MICROSURFACEAUTOMATIC = false;
  36218. _this.LODBASEDMICROSFURACE = false;
  36219. _this.MICROSURFACEMAP = false;
  36220. _this.MICROSURFACEMAPDIRECTUV = 0;
  36221. _this.METALLICWORKFLOW = false;
  36222. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36223. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36224. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36225. _this.AOSTOREINMETALMAPRED = false;
  36226. _this.ENVIRONMENTBRDF = false;
  36227. _this.NORMAL = false;
  36228. _this.TANGENT = false;
  36229. _this.BUMP = false;
  36230. _this.BUMPDIRECTUV = 0;
  36231. _this.PARALLAX = false;
  36232. _this.PARALLAXOCCLUSION = false;
  36233. _this.NORMALXYSCALE = true;
  36234. _this.LIGHTMAP = false;
  36235. _this.LIGHTMAPDIRECTUV = 0;
  36236. _this.USELIGHTMAPASSHADOWMAP = false;
  36237. _this.REFLECTION = false;
  36238. _this.REFLECTIONMAP_3D = false;
  36239. _this.REFLECTIONMAP_SPHERICAL = false;
  36240. _this.REFLECTIONMAP_PLANAR = false;
  36241. _this.REFLECTIONMAP_CUBIC = false;
  36242. _this.REFLECTIONMAP_PROJECTION = false;
  36243. _this.REFLECTIONMAP_SKYBOX = false;
  36244. _this.REFLECTIONMAP_EXPLICIT = false;
  36245. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36246. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36247. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36248. _this.INVERTCUBICMAP = false;
  36249. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36250. _this.USESPHERICALINVERTEX = false;
  36251. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36252. _this.LODINREFLECTIONALPHA = false;
  36253. _this.GAMMAREFLECTION = false;
  36254. _this.RADIANCEOCCLUSION = false;
  36255. _this.HORIZONOCCLUSION = false;
  36256. _this.REFRACTION = false;
  36257. _this.REFRACTIONMAP_3D = false;
  36258. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36259. _this.LODINREFRACTIONALPHA = false;
  36260. _this.GAMMAREFRACTION = false;
  36261. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36262. _this.INSTANCES = false;
  36263. _this.NUM_BONE_INFLUENCERS = 0;
  36264. _this.BonesPerMesh = 0;
  36265. _this.NONUNIFORMSCALING = false;
  36266. _this.MORPHTARGETS = false;
  36267. _this.MORPHTARGETS_NORMAL = false;
  36268. _this.MORPHTARGETS_TANGENT = false;
  36269. _this.NUM_MORPH_INFLUENCERS = 0;
  36270. _this.IMAGEPROCESSING = false;
  36271. _this.VIGNETTE = false;
  36272. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36273. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36274. _this.TONEMAPPING = false;
  36275. _this.CONTRAST = false;
  36276. _this.COLORCURVES = false;
  36277. _this.COLORGRADING = false;
  36278. _this.COLORGRADING3D = false;
  36279. _this.SAMPLER3DGREENDEPTH = false;
  36280. _this.SAMPLER3DBGRMAP = false;
  36281. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36282. _this.EXPOSURE = false;
  36283. _this.USEPHYSICALLIGHTFALLOFF = false;
  36284. _this.TWOSIDEDLIGHTING = false;
  36285. _this.SHADOWFLOAT = false;
  36286. _this.CLIPPLANE = false;
  36287. _this.POINTSIZE = false;
  36288. _this.FOG = false;
  36289. _this.LOGARITHMICDEPTH = false;
  36290. _this.FORCENORMALFORWARD = false;
  36291. _this.rebuild();
  36292. return _this;
  36293. }
  36294. PBRMaterialDefines.prototype.reset = function () {
  36295. _super.prototype.reset.call(this);
  36296. this.ALPHATESTVALUE = 0.5;
  36297. this.PBR = true;
  36298. };
  36299. return PBRMaterialDefines;
  36300. }(BABYLON.MaterialDefines));
  36301. /**
  36302. * The Physically based material base class of BJS.
  36303. *
  36304. * This offers the main features of a standard PBR material.
  36305. * For more information, please refer to the documentation :
  36306. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36307. */
  36308. var PBRBaseMaterial = /** @class */ (function (_super) {
  36309. __extends(PBRBaseMaterial, _super);
  36310. /**
  36311. * Instantiates a new PBRMaterial instance.
  36312. *
  36313. * @param name The material name
  36314. * @param scene The scene the material will be use in.
  36315. */
  36316. function PBRBaseMaterial(name, scene) {
  36317. var _this = _super.call(this, name, scene) || this;
  36318. /**
  36319. * Intensity of the direct lights e.g. the four lights available in your scene.
  36320. * This impacts both the direct diffuse and specular highlights.
  36321. */
  36322. _this._directIntensity = 1.0;
  36323. /**
  36324. * Intensity of the emissive part of the material.
  36325. * This helps controlling the emissive effect without modifying the emissive color.
  36326. */
  36327. _this._emissiveIntensity = 1.0;
  36328. /**
  36329. * Intensity of the environment e.g. how much the environment will light the object
  36330. * either through harmonics for rough material or through the refelction for shiny ones.
  36331. */
  36332. _this._environmentIntensity = 1.0;
  36333. /**
  36334. * This is a special control allowing the reduction of the specular highlights coming from the
  36335. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36336. */
  36337. _this._specularIntensity = 1.0;
  36338. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36339. /**
  36340. * Debug Control allowing disabling the bump map on this material.
  36341. */
  36342. _this._disableBumpMap = false;
  36343. /**
  36344. * AKA Occlusion Texture Intensity in other nomenclature.
  36345. */
  36346. _this._ambientTextureStrength = 1.0;
  36347. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36348. /**
  36349. * AKA Diffuse Color in other nomenclature.
  36350. */
  36351. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36352. /**
  36353. * AKA Specular Color in other nomenclature.
  36354. */
  36355. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36356. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36357. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36358. /**
  36359. * AKA Glossiness in other nomenclature.
  36360. */
  36361. _this._microSurface = 0.9;
  36362. /**
  36363. * source material index of refraction (IOR)' / 'destination material IOR.
  36364. */
  36365. _this._indexOfRefraction = 0.66;
  36366. /**
  36367. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36368. */
  36369. _this._invertRefractionY = false;
  36370. /**
  36371. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36372. * Materials half opaque for instance using refraction could benefit from this control.
  36373. */
  36374. _this._linkRefractionWithTransparency = false;
  36375. _this._useLightmapAsShadowmap = false;
  36376. /**
  36377. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36378. * makes the reflect vector face the model (under horizon).
  36379. */
  36380. _this._useHorizonOcclusion = true;
  36381. /**
  36382. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36383. * too much the area relying on ambient texture to define their ambient occlusion.
  36384. */
  36385. _this._useRadianceOcclusion = true;
  36386. /**
  36387. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36388. */
  36389. _this._useAlphaFromAlbedoTexture = false;
  36390. /**
  36391. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36392. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36393. */
  36394. _this._useSpecularOverAlpha = true;
  36395. /**
  36396. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36397. */
  36398. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36399. /**
  36400. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36401. */
  36402. _this._useRoughnessFromMetallicTextureAlpha = true;
  36403. /**
  36404. * Specifies if the metallic texture contains the roughness information in its green channel.
  36405. */
  36406. _this._useRoughnessFromMetallicTextureGreen = false;
  36407. /**
  36408. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36409. */
  36410. _this._useMetallnessFromMetallicTextureBlue = false;
  36411. /**
  36412. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36413. */
  36414. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36415. /**
  36416. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36417. */
  36418. _this._useAmbientInGrayScale = false;
  36419. /**
  36420. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36421. * The material will try to infer what glossiness each pixel should be.
  36422. */
  36423. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36424. /**
  36425. * BJS is using an harcoded light falloff based on a manually sets up range.
  36426. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36427. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36428. */
  36429. _this._usePhysicalLightFalloff = true;
  36430. /**
  36431. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36432. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36433. */
  36434. _this._useRadianceOverAlpha = true;
  36435. /**
  36436. * Allows using the bump map in parallax mode.
  36437. */
  36438. _this._useParallax = false;
  36439. /**
  36440. * Allows using the bump map in parallax occlusion mode.
  36441. */
  36442. _this._useParallaxOcclusion = false;
  36443. /**
  36444. * Controls the scale bias of the parallax mode.
  36445. */
  36446. _this._parallaxScaleBias = 0.05;
  36447. /**
  36448. * If sets to true, disables all the lights affecting the material.
  36449. */
  36450. _this._disableLighting = false;
  36451. /**
  36452. * Number of Simultaneous lights allowed on the material.
  36453. */
  36454. _this._maxSimultaneousLights = 4;
  36455. /**
  36456. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36457. */
  36458. _this._invertNormalMapX = false;
  36459. /**
  36460. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36461. */
  36462. _this._invertNormalMapY = false;
  36463. /**
  36464. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36465. */
  36466. _this._twoSidedLighting = false;
  36467. /**
  36468. * Defines the alpha limits in alpha test mode.
  36469. */
  36470. _this._alphaCutOff = 0.4;
  36471. /**
  36472. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36473. */
  36474. _this._forceAlphaTest = false;
  36475. /**
  36476. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36477. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36478. */
  36479. _this._useAlphaFresnel = false;
  36480. /**
  36481. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36482. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36483. */
  36484. _this._useLinearAlphaFresnel = false;
  36485. /**
  36486. * The transparency mode of the material.
  36487. */
  36488. _this._transparencyMode = null;
  36489. /**
  36490. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36491. * from cos thetav and roughness:
  36492. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36493. */
  36494. _this._environmentBRDFTexture = null;
  36495. /**
  36496. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36497. */
  36498. _this._forceIrradianceInFragment = false;
  36499. /**
  36500. * Force normal to face away from face.
  36501. */
  36502. _this._forceNormalForward = false;
  36503. /**
  36504. * Force metallic workflow.
  36505. */
  36506. _this._forceMetallicWorkflow = false;
  36507. _this._renderTargets = new BABYLON.SmartArray(16);
  36508. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36509. // Setup the default processing configuration to the scene.
  36510. _this._attachImageProcessingConfiguration(null);
  36511. _this.getRenderTargetTextures = function () {
  36512. _this._renderTargets.reset();
  36513. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36514. _this._renderTargets.push(_this._reflectionTexture);
  36515. }
  36516. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36517. _this._renderTargets.push(_this._refractionTexture);
  36518. }
  36519. return _this._renderTargets;
  36520. };
  36521. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36522. return _this;
  36523. }
  36524. /**
  36525. * Attaches a new image processing configuration to the PBR Material.
  36526. * @param configuration
  36527. */
  36528. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36529. var _this = this;
  36530. if (configuration === this._imageProcessingConfiguration) {
  36531. return;
  36532. }
  36533. // Detaches observer.
  36534. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36535. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36536. }
  36537. // Pick the scene configuration if needed.
  36538. if (!configuration) {
  36539. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36540. }
  36541. else {
  36542. this._imageProcessingConfiguration = configuration;
  36543. }
  36544. // Attaches observer.
  36545. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36546. _this._markAllSubMeshesAsImageProcessingDirty();
  36547. });
  36548. };
  36549. PBRBaseMaterial.prototype.getClassName = function () {
  36550. return "PBRBaseMaterial";
  36551. };
  36552. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36553. get: function () {
  36554. return this._useLogarithmicDepth;
  36555. },
  36556. set: function (value) {
  36557. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36558. },
  36559. enumerable: true,
  36560. configurable: true
  36561. });
  36562. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36563. /**
  36564. * Gets the current transparency mode.
  36565. */
  36566. get: function () {
  36567. return this._transparencyMode;
  36568. },
  36569. /**
  36570. * Sets the transparency mode of the material.
  36571. */
  36572. set: function (value) {
  36573. if (this._transparencyMode === value) {
  36574. return;
  36575. }
  36576. this._transparencyMode = value;
  36577. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36578. this._markAllSubMeshesAsTexturesDirty();
  36579. },
  36580. enumerable: true,
  36581. configurable: true
  36582. });
  36583. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36584. /**
  36585. * Returns true if alpha blending should be disabled.
  36586. */
  36587. get: function () {
  36588. return (this._linkRefractionWithTransparency ||
  36589. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36590. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36591. },
  36592. enumerable: true,
  36593. configurable: true
  36594. });
  36595. /**
  36596. * Specifies whether or not this material should be rendered in alpha blend mode.
  36597. */
  36598. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36599. if (this._disableAlphaBlending) {
  36600. return false;
  36601. }
  36602. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36603. };
  36604. /**
  36605. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36606. */
  36607. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36608. if (this._disableAlphaBlending) {
  36609. return false;
  36610. }
  36611. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36612. };
  36613. /**
  36614. * Specifies whether or not this material should be rendered in alpha test mode.
  36615. */
  36616. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36617. if (this._forceAlphaTest) {
  36618. return true;
  36619. }
  36620. if (this._linkRefractionWithTransparency) {
  36621. return false;
  36622. }
  36623. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36624. };
  36625. /**
  36626. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36627. */
  36628. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36629. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36630. };
  36631. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36632. return this._albedoTexture;
  36633. };
  36634. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36635. var _this = this;
  36636. if (subMesh.effect && this.isFrozen) {
  36637. if (this._wasPreviouslyReady) {
  36638. return true;
  36639. }
  36640. }
  36641. if (!subMesh._materialDefines) {
  36642. subMesh._materialDefines = new PBRMaterialDefines();
  36643. }
  36644. var scene = this.getScene();
  36645. var defines = subMesh._materialDefines;
  36646. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36647. if (defines._renderId === scene.getRenderId()) {
  36648. return true;
  36649. }
  36650. }
  36651. var engine = scene.getEngine();
  36652. // Lights
  36653. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36654. defines._needNormals = true;
  36655. // Textures
  36656. if (defines._areTexturesDirty) {
  36657. defines._needUVs = false;
  36658. if (scene.texturesEnabled) {
  36659. if (scene.getEngine().getCaps().textureLOD) {
  36660. defines.LODBASEDMICROSFURACE = true;
  36661. }
  36662. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36663. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36664. return false;
  36665. }
  36666. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36667. }
  36668. else {
  36669. defines.ALBEDO = false;
  36670. }
  36671. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36672. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36673. return false;
  36674. }
  36675. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36676. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36677. }
  36678. else {
  36679. defines.AMBIENT = false;
  36680. }
  36681. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36682. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36683. return false;
  36684. }
  36685. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36686. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36687. }
  36688. else {
  36689. defines.OPACITY = false;
  36690. }
  36691. var reflectionTexture = this._getReflectionTexture();
  36692. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36693. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36694. return false;
  36695. }
  36696. defines.REFLECTION = true;
  36697. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36698. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36699. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36700. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36701. defines.INVERTCUBICMAP = true;
  36702. }
  36703. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36704. switch (reflectionTexture.coordinatesMode) {
  36705. case BABYLON.Texture.CUBIC_MODE:
  36706. case BABYLON.Texture.INVCUBIC_MODE:
  36707. defines.REFLECTIONMAP_CUBIC = true;
  36708. break;
  36709. case BABYLON.Texture.EXPLICIT_MODE:
  36710. defines.REFLECTIONMAP_EXPLICIT = true;
  36711. break;
  36712. case BABYLON.Texture.PLANAR_MODE:
  36713. defines.REFLECTIONMAP_PLANAR = true;
  36714. break;
  36715. case BABYLON.Texture.PROJECTION_MODE:
  36716. defines.REFLECTIONMAP_PROJECTION = true;
  36717. break;
  36718. case BABYLON.Texture.SKYBOX_MODE:
  36719. defines.REFLECTIONMAP_SKYBOX = true;
  36720. break;
  36721. case BABYLON.Texture.SPHERICAL_MODE:
  36722. defines.REFLECTIONMAP_SPHERICAL = true;
  36723. break;
  36724. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36725. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36726. break;
  36727. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36728. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36729. break;
  36730. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36731. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36732. break;
  36733. }
  36734. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36735. if (reflectionTexture.sphericalPolynomial) {
  36736. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36737. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36738. defines.USESPHERICALINVERTEX = false;
  36739. }
  36740. else {
  36741. defines.USESPHERICALINVERTEX = true;
  36742. }
  36743. }
  36744. }
  36745. }
  36746. else {
  36747. defines.REFLECTION = false;
  36748. defines.REFLECTIONMAP_3D = false;
  36749. defines.REFLECTIONMAP_SPHERICAL = false;
  36750. defines.REFLECTIONMAP_PLANAR = false;
  36751. defines.REFLECTIONMAP_CUBIC = false;
  36752. defines.REFLECTIONMAP_PROJECTION = false;
  36753. defines.REFLECTIONMAP_SKYBOX = false;
  36754. defines.REFLECTIONMAP_EXPLICIT = false;
  36755. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36756. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36757. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36758. defines.INVERTCUBICMAP = false;
  36759. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36760. defines.USESPHERICALINVERTEX = false;
  36761. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36762. defines.LODINREFLECTIONALPHA = false;
  36763. defines.GAMMAREFLECTION = false;
  36764. }
  36765. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36766. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36767. return false;
  36768. }
  36769. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36770. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36771. }
  36772. else {
  36773. defines.LIGHTMAP = false;
  36774. }
  36775. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36776. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36777. return false;
  36778. }
  36779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36780. }
  36781. else {
  36782. defines.EMISSIVE = false;
  36783. }
  36784. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36785. if (this._metallicTexture) {
  36786. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36787. return false;
  36788. }
  36789. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36790. defines.METALLICWORKFLOW = true;
  36791. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36792. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36793. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36794. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36795. }
  36796. else if (this._reflectivityTexture) {
  36797. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36798. return false;
  36799. }
  36800. defines.METALLICWORKFLOW = false;
  36801. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36802. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36803. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36804. }
  36805. else {
  36806. defines.METALLICWORKFLOW = false;
  36807. defines.REFLECTIVITY = false;
  36808. }
  36809. if (this._microSurfaceTexture) {
  36810. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36811. return false;
  36812. }
  36813. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36814. }
  36815. else {
  36816. defines.MICROSURFACEMAP = false;
  36817. }
  36818. }
  36819. else {
  36820. defines.REFLECTIVITY = false;
  36821. defines.MICROSURFACEMAP = false;
  36822. }
  36823. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36824. // Bump texure can not be none blocking.
  36825. if (!this._bumpTexture.isReady()) {
  36826. return false;
  36827. }
  36828. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36829. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36830. defines.PARALLAX = true;
  36831. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36832. }
  36833. else {
  36834. defines.PARALLAX = false;
  36835. }
  36836. }
  36837. else {
  36838. defines.BUMP = false;
  36839. }
  36840. var refractionTexture = this._getRefractionTexture();
  36841. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36842. if (!refractionTexture.isReadyOrNotBlocking()) {
  36843. return false;
  36844. }
  36845. defines.REFRACTION = true;
  36846. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36847. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36848. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36849. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36850. if (this._linkRefractionWithTransparency) {
  36851. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36852. }
  36853. }
  36854. else {
  36855. defines.REFRACTION = false;
  36856. }
  36857. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36858. // This is blocking.
  36859. if (!this._environmentBRDFTexture.isReady()) {
  36860. return false;
  36861. }
  36862. defines.ENVIRONMENTBRDF = true;
  36863. }
  36864. else {
  36865. defines.ENVIRONMENTBRDF = false;
  36866. }
  36867. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36868. defines.ALPHAFROMALBEDO = true;
  36869. }
  36870. else {
  36871. defines.ALPHAFROMALBEDO = false;
  36872. }
  36873. }
  36874. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36875. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36876. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36877. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36878. defines.METALLICWORKFLOW = true;
  36879. }
  36880. else {
  36881. defines.METALLICWORKFLOW = false;
  36882. }
  36883. if (!this.backFaceCulling && this._twoSidedLighting) {
  36884. defines.TWOSIDEDLIGHTING = true;
  36885. }
  36886. else {
  36887. defines.TWOSIDEDLIGHTING = false;
  36888. }
  36889. defines.ALPHATESTVALUE = this._alphaCutOff;
  36890. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36891. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36892. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36893. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36894. }
  36895. if (defines._areImageProcessingDirty) {
  36896. if (!this._imageProcessingConfiguration.isReady()) {
  36897. return false;
  36898. }
  36899. this._imageProcessingConfiguration.prepareDefines(defines);
  36900. }
  36901. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36902. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36903. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36904. // Misc.
  36905. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36906. // Values that need to be evaluated on every frame
  36907. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36908. // Attribs
  36909. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36910. var bufferMesh = null;
  36911. if (mesh instanceof BABYLON.InstancedMesh) {
  36912. bufferMesh = mesh.sourceMesh;
  36913. }
  36914. else if (mesh instanceof BABYLON.Mesh) {
  36915. bufferMesh = mesh;
  36916. }
  36917. if (bufferMesh) {
  36918. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36919. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36920. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36921. var normals = normalVertexBuffer.getData();
  36922. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36923. var strideSize = normalVertexBuffer.getStrideSize();
  36924. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36925. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36926. defines.NORMAL = false;
  36927. }
  36928. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36929. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36930. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36931. var tangents = tangentVertexBuffer.getData();
  36932. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36933. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36934. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36935. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36936. defines.TANGENT = false;
  36937. }
  36938. }
  36939. }
  36940. else {
  36941. if (!scene.getEngine().getCaps().standardDerivatives) {
  36942. bufferMesh.createNormals(true);
  36943. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36944. }
  36945. }
  36946. }
  36947. }
  36948. // Get correct effect
  36949. if (defines.isDirty) {
  36950. defines.markAsProcessed();
  36951. scene.resetCachedMaterial();
  36952. // Fallbacks
  36953. var fallbacks = new BABYLON.EffectFallbacks();
  36954. var fallbackRank = 0;
  36955. if (defines.USESPHERICALINVERTEX) {
  36956. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36957. }
  36958. if (defines.FOG) {
  36959. fallbacks.addFallback(fallbackRank, "FOG");
  36960. }
  36961. if (defines.POINTSIZE) {
  36962. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36963. }
  36964. if (defines.LOGARITHMICDEPTH) {
  36965. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36966. }
  36967. if (defines.PARALLAX) {
  36968. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36969. }
  36970. if (defines.PARALLAXOCCLUSION) {
  36971. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36972. }
  36973. if (defines.ENVIRONMENTBRDF) {
  36974. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36975. }
  36976. if (defines.TANGENT) {
  36977. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36978. }
  36979. if (defines.BUMP) {
  36980. fallbacks.addFallback(fallbackRank++, "BUMP");
  36981. }
  36982. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36983. if (defines.SPECULARTERM) {
  36984. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36985. }
  36986. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36987. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36988. }
  36989. if (defines.LIGHTMAP) {
  36990. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36991. }
  36992. if (defines.NORMAL) {
  36993. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36994. }
  36995. if (defines.AMBIENT) {
  36996. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36997. }
  36998. if (defines.EMISSIVE) {
  36999. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37000. }
  37001. if (defines.VERTEXCOLOR) {
  37002. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37003. }
  37004. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37005. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37006. }
  37007. if (defines.MORPHTARGETS) {
  37008. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37009. }
  37010. //Attributes
  37011. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37012. if (defines.NORMAL) {
  37013. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37014. }
  37015. if (defines.TANGENT) {
  37016. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37017. }
  37018. if (defines.UV1) {
  37019. attribs.push(BABYLON.VertexBuffer.UVKind);
  37020. }
  37021. if (defines.UV2) {
  37022. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37023. }
  37024. if (defines.VERTEXCOLOR) {
  37025. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37026. }
  37027. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37028. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37029. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37030. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37031. "vFogInfos", "vFogColor", "pointSize",
  37032. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37033. "mBones",
  37034. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37035. "vLightingIntensity",
  37036. "logarithmicDepthConstant",
  37037. "vSphericalX", "vSphericalY", "vSphericalZ",
  37038. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37039. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37040. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37041. "vTangentSpaceParams"
  37042. ];
  37043. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37044. "bumpSampler", "lightmapSampler", "opacitySampler",
  37045. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37046. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37047. "microSurfaceSampler", "environmentBrdfSampler"];
  37048. var uniformBuffers = ["Material", "Scene"];
  37049. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37050. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37051. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37052. uniformsNames: uniforms,
  37053. uniformBuffersNames: uniformBuffers,
  37054. samplers: samplers,
  37055. defines: defines,
  37056. maxSimultaneousLights: this._maxSimultaneousLights
  37057. });
  37058. var onCompiled = function (effect) {
  37059. if (_this.onCompiled) {
  37060. _this.onCompiled(effect);
  37061. }
  37062. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37063. };
  37064. var join = defines.toString();
  37065. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37066. attributes: attribs,
  37067. uniformsNames: uniforms,
  37068. uniformBuffersNames: uniformBuffers,
  37069. samplers: samplers,
  37070. defines: join,
  37071. fallbacks: fallbacks,
  37072. onCompiled: onCompiled,
  37073. onError: this.onError,
  37074. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37075. }, engine), defines);
  37076. this.buildUniformLayout();
  37077. }
  37078. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37079. return false;
  37080. }
  37081. defines._renderId = scene.getRenderId();
  37082. this._wasPreviouslyReady = true;
  37083. return true;
  37084. };
  37085. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37086. // Order is important !
  37087. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37088. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37089. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37090. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37091. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37092. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37093. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37094. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37095. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37096. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37097. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37098. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37099. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37100. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37101. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37102. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37103. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37104. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37105. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37106. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37107. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37108. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37109. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37110. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37111. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37112. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37113. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37114. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37115. this._uniformBuffer.addUniform("pointSize", 1);
  37116. this._uniformBuffer.create();
  37117. };
  37118. PBRBaseMaterial.prototype.unbind = function () {
  37119. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37120. this._uniformBuffer.setTexture("reflectionSampler", null);
  37121. }
  37122. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37123. this._uniformBuffer.setTexture("refractionSampler", null);
  37124. }
  37125. _super.prototype.unbind.call(this);
  37126. };
  37127. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37128. this._activeEffect.setMatrix("world", world);
  37129. };
  37130. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37131. var scene = this.getScene();
  37132. var defines = subMesh._materialDefines;
  37133. if (!defines) {
  37134. return;
  37135. }
  37136. var effect = subMesh.effect;
  37137. if (!effect) {
  37138. return;
  37139. }
  37140. this._activeEffect = effect;
  37141. // Matrices
  37142. this.bindOnlyWorldMatrix(world);
  37143. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37144. // Bones
  37145. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37146. var reflectionTexture = null;
  37147. if (mustRebind) {
  37148. this._uniformBuffer.bindToEffect(effect, "Material");
  37149. this.bindViewProjection(effect);
  37150. reflectionTexture = this._getReflectionTexture();
  37151. var refractionTexture = this._getRefractionTexture();
  37152. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37153. // Texture uniforms
  37154. if (scene.texturesEnabled) {
  37155. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37156. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37157. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37158. }
  37159. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37160. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37161. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37162. }
  37163. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37164. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37165. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37166. }
  37167. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37168. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37169. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37170. var polynomials = reflectionTexture.sphericalPolynomial;
  37171. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37172. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37173. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37174. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37175. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37176. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37177. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37178. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37179. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37180. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37181. }
  37182. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37183. }
  37184. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37185. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37186. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37187. }
  37188. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37189. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37190. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37191. }
  37192. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37193. if (this._metallicTexture) {
  37194. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37195. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37196. }
  37197. else if (this._reflectivityTexture) {
  37198. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37199. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37200. }
  37201. if (this._microSurfaceTexture) {
  37202. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37203. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37204. }
  37205. }
  37206. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37207. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37208. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37209. if (scene._mirroredCameraPosition) {
  37210. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37211. }
  37212. else {
  37213. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37214. }
  37215. }
  37216. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37217. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37218. var depth = 1.0;
  37219. if (!refractionTexture.isCube) {
  37220. if (refractionTexture.depth) {
  37221. depth = refractionTexture.depth;
  37222. }
  37223. }
  37224. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37225. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37226. }
  37227. }
  37228. // Point size
  37229. if (this.pointsCloud) {
  37230. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37231. }
  37232. // Colors
  37233. if (defines.METALLICWORKFLOW) {
  37234. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37235. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37236. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37237. }
  37238. else {
  37239. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37240. }
  37241. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37242. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37243. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37244. // Misc
  37245. this._lightingInfos.x = this._directIntensity;
  37246. this._lightingInfos.y = this._emissiveIntensity;
  37247. this._lightingInfos.z = this._environmentIntensity;
  37248. this._lightingInfos.w = this._specularIntensity;
  37249. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37250. }
  37251. // Textures
  37252. if (scene.texturesEnabled) {
  37253. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37254. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37255. }
  37256. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37257. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37258. }
  37259. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37260. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37261. }
  37262. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37263. if (defines.LODBASEDMICROSFURACE) {
  37264. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37265. }
  37266. else {
  37267. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37268. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37269. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37270. }
  37271. }
  37272. if (defines.ENVIRONMENTBRDF) {
  37273. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37274. }
  37275. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37276. if (defines.LODBASEDMICROSFURACE) {
  37277. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37278. }
  37279. else {
  37280. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37281. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37282. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37283. }
  37284. }
  37285. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37286. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37287. }
  37288. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37289. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37290. }
  37291. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37292. if (this._metallicTexture) {
  37293. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37294. }
  37295. else if (this._reflectivityTexture) {
  37296. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37297. }
  37298. if (this._microSurfaceTexture) {
  37299. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37300. }
  37301. }
  37302. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37303. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37304. }
  37305. }
  37306. // Clip plane
  37307. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37308. // Colors
  37309. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37310. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37311. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37312. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37313. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37314. }
  37315. if (mustRebind || !this.isFrozen) {
  37316. // Lights
  37317. if (scene.lightsEnabled && !this._disableLighting) {
  37318. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37319. }
  37320. // View
  37321. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37322. this.bindView(effect);
  37323. }
  37324. // Fog
  37325. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37326. // Morph targets
  37327. if (defines.NUM_MORPH_INFLUENCERS) {
  37328. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37329. }
  37330. // image processing
  37331. this._imageProcessingConfiguration.bind(this._activeEffect);
  37332. // Log. depth
  37333. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37334. }
  37335. this._uniformBuffer.update();
  37336. this._afterBind(mesh);
  37337. };
  37338. PBRBaseMaterial.prototype.getAnimatables = function () {
  37339. var results = [];
  37340. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37341. results.push(this._albedoTexture);
  37342. }
  37343. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37344. results.push(this._ambientTexture);
  37345. }
  37346. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37347. results.push(this._opacityTexture);
  37348. }
  37349. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37350. results.push(this._reflectionTexture);
  37351. }
  37352. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37353. results.push(this._emissiveTexture);
  37354. }
  37355. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37356. results.push(this._metallicTexture);
  37357. }
  37358. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37359. results.push(this._reflectivityTexture);
  37360. }
  37361. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37362. results.push(this._bumpTexture);
  37363. }
  37364. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37365. results.push(this._lightmapTexture);
  37366. }
  37367. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37368. results.push(this._refractionTexture);
  37369. }
  37370. return results;
  37371. };
  37372. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37373. if (this._reflectionTexture) {
  37374. return this._reflectionTexture;
  37375. }
  37376. return this.getScene().environmentTexture;
  37377. };
  37378. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37379. if (this._refractionTexture) {
  37380. return this._refractionTexture;
  37381. }
  37382. if (this._linkRefractionWithTransparency) {
  37383. return this.getScene().environmentTexture;
  37384. }
  37385. return null;
  37386. };
  37387. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37388. if (forceDisposeTextures) {
  37389. if (this._albedoTexture) {
  37390. this._albedoTexture.dispose();
  37391. }
  37392. if (this._ambientTexture) {
  37393. this._ambientTexture.dispose();
  37394. }
  37395. if (this._opacityTexture) {
  37396. this._opacityTexture.dispose();
  37397. }
  37398. if (this._reflectionTexture) {
  37399. this._reflectionTexture.dispose();
  37400. }
  37401. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37402. this._environmentBRDFTexture.dispose();
  37403. }
  37404. if (this._emissiveTexture) {
  37405. this._emissiveTexture.dispose();
  37406. }
  37407. if (this._metallicTexture) {
  37408. this._metallicTexture.dispose();
  37409. }
  37410. if (this._reflectivityTexture) {
  37411. this._reflectivityTexture.dispose();
  37412. }
  37413. if (this._bumpTexture) {
  37414. this._bumpTexture.dispose();
  37415. }
  37416. if (this._lightmapTexture) {
  37417. this._lightmapTexture.dispose();
  37418. }
  37419. if (this._refractionTexture) {
  37420. this._refractionTexture.dispose();
  37421. }
  37422. }
  37423. this._renderTargets.dispose();
  37424. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37425. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37426. }
  37427. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37428. };
  37429. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37430. __decorate([
  37431. BABYLON.serializeAsImageProcessingConfiguration()
  37432. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37433. __decorate([
  37434. BABYLON.serialize()
  37435. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37436. __decorate([
  37437. BABYLON.serialize()
  37438. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37439. return PBRBaseMaterial;
  37440. }(BABYLON.PushMaterial));
  37441. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37442. })(BABYLON || (BABYLON = {}));
  37443. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37444. var BABYLON;
  37445. (function (BABYLON) {
  37446. /**
  37447. * The Physically based simple base material of BJS.
  37448. *
  37449. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37450. * It is used as the base class for both the specGloss and metalRough conventions.
  37451. */
  37452. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37453. __extends(PBRBaseSimpleMaterial, _super);
  37454. /**
  37455. * Instantiates a new PBRMaterial instance.
  37456. *
  37457. * @param name The material name
  37458. * @param scene The scene the material will be use in.
  37459. */
  37460. function PBRBaseSimpleMaterial(name, scene) {
  37461. var _this = _super.call(this, name, scene) || this;
  37462. /**
  37463. * Number of Simultaneous lights allowed on the material.
  37464. */
  37465. _this.maxSimultaneousLights = 4;
  37466. /**
  37467. * If sets to true, disables all the lights affecting the material.
  37468. */
  37469. _this.disableLighting = false;
  37470. /**
  37471. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37472. */
  37473. _this.invertNormalMapX = false;
  37474. /**
  37475. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37476. */
  37477. _this.invertNormalMapY = false;
  37478. /**
  37479. * Emissivie color used to self-illuminate the model.
  37480. */
  37481. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37482. /**
  37483. * Occlusion Channel Strenght.
  37484. */
  37485. _this.occlusionStrength = 1.0;
  37486. _this.useLightmapAsShadowmap = false;
  37487. _this._useAlphaFromAlbedoTexture = true;
  37488. _this._useAmbientInGrayScale = true;
  37489. return _this;
  37490. }
  37491. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37492. /**
  37493. * Gets the current double sided mode.
  37494. */
  37495. get: function () {
  37496. return this._twoSidedLighting;
  37497. },
  37498. /**
  37499. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37500. */
  37501. set: function (value) {
  37502. if (this._twoSidedLighting === value) {
  37503. return;
  37504. }
  37505. this._twoSidedLighting = value;
  37506. this.backFaceCulling = !value;
  37507. this._markAllSubMeshesAsTexturesDirty();
  37508. },
  37509. enumerable: true,
  37510. configurable: true
  37511. });
  37512. /**
  37513. * Return the active textures of the material.
  37514. */
  37515. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37516. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37517. if (this.environmentTexture) {
  37518. activeTextures.push(this.environmentTexture);
  37519. }
  37520. if (this.normalTexture) {
  37521. activeTextures.push(this.normalTexture);
  37522. }
  37523. if (this.emissiveTexture) {
  37524. activeTextures.push(this.emissiveTexture);
  37525. }
  37526. if (this.occlusionTexture) {
  37527. activeTextures.push(this.occlusionTexture);
  37528. }
  37529. if (this.lightmapTexture) {
  37530. activeTextures.push(this.lightmapTexture);
  37531. }
  37532. return activeTextures;
  37533. };
  37534. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37535. if (_super.prototype.hasTexture.call(this, texture)) {
  37536. return true;
  37537. }
  37538. if (this.lightmapTexture === texture) {
  37539. return true;
  37540. }
  37541. return false;
  37542. };
  37543. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37544. return "PBRBaseSimpleMaterial";
  37545. };
  37546. __decorate([
  37547. BABYLON.serialize(),
  37548. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37549. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37550. __decorate([
  37551. BABYLON.serialize(),
  37552. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37553. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37554. __decorate([
  37555. BABYLON.serializeAsTexture(),
  37556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37557. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37558. __decorate([
  37559. BABYLON.serialize(),
  37560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37561. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37562. __decorate([
  37563. BABYLON.serialize(),
  37564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37565. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37566. __decorate([
  37567. BABYLON.serializeAsTexture(),
  37568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37569. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37570. __decorate([
  37571. BABYLON.serializeAsColor3("emissive"),
  37572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37573. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37574. __decorate([
  37575. BABYLON.serializeAsTexture(),
  37576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37577. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37578. __decorate([
  37579. BABYLON.serialize(),
  37580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37581. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37582. __decorate([
  37583. BABYLON.serializeAsTexture(),
  37584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37585. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37586. __decorate([
  37587. BABYLON.serialize(),
  37588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37589. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37590. __decorate([
  37591. BABYLON.serialize()
  37592. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37593. __decorate([
  37594. BABYLON.serializeAsTexture(),
  37595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37596. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37597. __decorate([
  37598. BABYLON.serialize(),
  37599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37600. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37601. return PBRBaseSimpleMaterial;
  37602. }(BABYLON.PBRBaseMaterial));
  37603. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37604. })(BABYLON || (BABYLON = {}));
  37605. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37606. var BABYLON;
  37607. (function (BABYLON) {
  37608. /**
  37609. * The Physically based material of BJS.
  37610. *
  37611. * This offers the main features of a standard PBR material.
  37612. * For more information, please refer to the documentation :
  37613. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37614. */
  37615. var PBRMaterial = /** @class */ (function (_super) {
  37616. __extends(PBRMaterial, _super);
  37617. /**
  37618. * Instantiates a new PBRMaterial instance.
  37619. *
  37620. * @param name The material name
  37621. * @param scene The scene the material will be use in.
  37622. */
  37623. function PBRMaterial(name, scene) {
  37624. var _this = _super.call(this, name, scene) || this;
  37625. /**
  37626. * Intensity of the direct lights e.g. the four lights available in your scene.
  37627. * This impacts both the direct diffuse and specular highlights.
  37628. */
  37629. _this.directIntensity = 1.0;
  37630. /**
  37631. * Intensity of the emissive part of the material.
  37632. * This helps controlling the emissive effect without modifying the emissive color.
  37633. */
  37634. _this.emissiveIntensity = 1.0;
  37635. /**
  37636. * Intensity of the environment e.g. how much the environment will light the object
  37637. * either through harmonics for rough material or through the refelction for shiny ones.
  37638. */
  37639. _this.environmentIntensity = 1.0;
  37640. /**
  37641. * This is a special control allowing the reduction of the specular highlights coming from the
  37642. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37643. */
  37644. _this.specularIntensity = 1.0;
  37645. /**
  37646. * Debug Control allowing disabling the bump map on this material.
  37647. */
  37648. _this.disableBumpMap = false;
  37649. /**
  37650. * AKA Occlusion Texture Intensity in other nomenclature.
  37651. */
  37652. _this.ambientTextureStrength = 1.0;
  37653. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37654. /**
  37655. * AKA Diffuse Color in other nomenclature.
  37656. */
  37657. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37658. /**
  37659. * AKA Specular Color in other nomenclature.
  37660. */
  37661. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37662. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37663. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37664. /**
  37665. * AKA Glossiness in other nomenclature.
  37666. */
  37667. _this.microSurface = 1.0;
  37668. /**
  37669. * source material index of refraction (IOR)' / 'destination material IOR.
  37670. */
  37671. _this.indexOfRefraction = 0.66;
  37672. /**
  37673. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37674. */
  37675. _this.invertRefractionY = false;
  37676. /**
  37677. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37678. * Materials half opaque for instance using refraction could benefit from this control.
  37679. */
  37680. _this.linkRefractionWithTransparency = false;
  37681. _this.useLightmapAsShadowmap = false;
  37682. /**
  37683. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37684. */
  37685. _this.useAlphaFromAlbedoTexture = false;
  37686. /**
  37687. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37688. */
  37689. _this.forceAlphaTest = false;
  37690. /**
  37691. * Defines the alpha limits in alpha test mode.
  37692. */
  37693. _this.alphaCutOff = 0.4;
  37694. /**
  37695. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37696. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37697. */
  37698. _this.useSpecularOverAlpha = true;
  37699. /**
  37700. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37701. */
  37702. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37703. /**
  37704. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37705. */
  37706. _this.useRoughnessFromMetallicTextureAlpha = true;
  37707. /**
  37708. * Specifies if the metallic texture contains the roughness information in its green channel.
  37709. */
  37710. _this.useRoughnessFromMetallicTextureGreen = false;
  37711. /**
  37712. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37713. */
  37714. _this.useMetallnessFromMetallicTextureBlue = false;
  37715. /**
  37716. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37717. */
  37718. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37719. /**
  37720. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37721. */
  37722. _this.useAmbientInGrayScale = false;
  37723. /**
  37724. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37725. * The material will try to infer what glossiness each pixel should be.
  37726. */
  37727. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37728. /**
  37729. * BJS is using an harcoded light falloff based on a manually sets up range.
  37730. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37731. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37732. */
  37733. _this.usePhysicalLightFalloff = true;
  37734. /**
  37735. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37736. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37737. */
  37738. _this.useRadianceOverAlpha = true;
  37739. /**
  37740. * Allows using the bump map in parallax mode.
  37741. */
  37742. _this.useParallax = false;
  37743. /**
  37744. * Allows using the bump map in parallax occlusion mode.
  37745. */
  37746. _this.useParallaxOcclusion = false;
  37747. /**
  37748. * Controls the scale bias of the parallax mode.
  37749. */
  37750. _this.parallaxScaleBias = 0.05;
  37751. /**
  37752. * If sets to true, disables all the lights affecting the material.
  37753. */
  37754. _this.disableLighting = false;
  37755. /**
  37756. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37757. */
  37758. _this.forceIrradianceInFragment = false;
  37759. /**
  37760. * Number of Simultaneous lights allowed on the material.
  37761. */
  37762. _this.maxSimultaneousLights = 4;
  37763. /**
  37764. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37765. */
  37766. _this.invertNormalMapX = false;
  37767. /**
  37768. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37769. */
  37770. _this.invertNormalMapY = false;
  37771. /**
  37772. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37773. */
  37774. _this.twoSidedLighting = false;
  37775. /**
  37776. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37777. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37778. */
  37779. _this.useAlphaFresnel = false;
  37780. /**
  37781. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37782. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37783. */
  37784. _this.useLinearAlphaFresnel = false;
  37785. /**
  37786. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37787. * And/Or occlude the blended part.
  37788. */
  37789. _this.environmentBRDFTexture = null;
  37790. /**
  37791. * Force normal to face away from face.
  37792. */
  37793. _this.forceNormalForward = false;
  37794. /**
  37795. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37796. * makes the reflect vector face the model (under horizon).
  37797. */
  37798. _this.useHorizonOcclusion = true;
  37799. /**
  37800. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37801. * too much the area relying on ambient texture to define their ambient occlusion.
  37802. */
  37803. _this.useRadianceOcclusion = true;
  37804. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37805. return _this;
  37806. }
  37807. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37808. /**
  37809. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37810. */
  37811. get: function () {
  37812. return this._PBRMATERIAL_OPAQUE;
  37813. },
  37814. enumerable: true,
  37815. configurable: true
  37816. });
  37817. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37818. /**
  37819. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37820. */
  37821. get: function () {
  37822. return this._PBRMATERIAL_ALPHATEST;
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37828. /**
  37829. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37830. */
  37831. get: function () {
  37832. return this._PBRMATERIAL_ALPHABLEND;
  37833. },
  37834. enumerable: true,
  37835. configurable: true
  37836. });
  37837. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37838. /**
  37839. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37840. * They are also discarded below the alpha cutoff threshold to improve performances.
  37841. */
  37842. get: function () {
  37843. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37844. },
  37845. enumerable: true,
  37846. configurable: true
  37847. });
  37848. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37849. /**
  37850. * Gets the image processing configuration used either in this material.
  37851. */
  37852. get: function () {
  37853. return this._imageProcessingConfiguration;
  37854. },
  37855. /**
  37856. * Sets the Default image processing configuration used either in the this material.
  37857. *
  37858. * If sets to null, the scene one is in use.
  37859. */
  37860. set: function (value) {
  37861. this._attachImageProcessingConfiguration(value);
  37862. // Ensure the effect will be rebuilt.
  37863. this._markAllSubMeshesAsTexturesDirty();
  37864. },
  37865. enumerable: true,
  37866. configurable: true
  37867. });
  37868. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37869. /**
  37870. * Gets wether the color curves effect is enabled.
  37871. */
  37872. get: function () {
  37873. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37874. },
  37875. /**
  37876. * Sets wether the color curves effect is enabled.
  37877. */
  37878. set: function (value) {
  37879. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37880. },
  37881. enumerable: true,
  37882. configurable: true
  37883. });
  37884. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37885. /**
  37886. * Gets wether the color grading effect is enabled.
  37887. */
  37888. get: function () {
  37889. return this.imageProcessingConfiguration.colorGradingEnabled;
  37890. },
  37891. /**
  37892. * Gets wether the color grading effect is enabled.
  37893. */
  37894. set: function (value) {
  37895. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37896. },
  37897. enumerable: true,
  37898. configurable: true
  37899. });
  37900. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37901. /**
  37902. * Gets wether tonemapping is enabled or not.
  37903. */
  37904. get: function () {
  37905. return this._imageProcessingConfiguration.toneMappingEnabled;
  37906. },
  37907. /**
  37908. * Sets wether tonemapping is enabled or not
  37909. */
  37910. set: function (value) {
  37911. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37912. },
  37913. enumerable: true,
  37914. configurable: true
  37915. });
  37916. ;
  37917. ;
  37918. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37919. /**
  37920. * The camera exposure used on this material.
  37921. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37922. * This corresponds to a photographic exposure.
  37923. */
  37924. get: function () {
  37925. return this._imageProcessingConfiguration.exposure;
  37926. },
  37927. /**
  37928. * The camera exposure used on this material.
  37929. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37930. * This corresponds to a photographic exposure.
  37931. */
  37932. set: function (value) {
  37933. this._imageProcessingConfiguration.exposure = value;
  37934. },
  37935. enumerable: true,
  37936. configurable: true
  37937. });
  37938. ;
  37939. ;
  37940. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37941. /**
  37942. * Gets The camera contrast used on this material.
  37943. */
  37944. get: function () {
  37945. return this._imageProcessingConfiguration.contrast;
  37946. },
  37947. /**
  37948. * Sets The camera contrast used on this material.
  37949. */
  37950. set: function (value) {
  37951. this._imageProcessingConfiguration.contrast = value;
  37952. },
  37953. enumerable: true,
  37954. configurable: true
  37955. });
  37956. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37957. /**
  37958. * Gets the Color Grading 2D Lookup Texture.
  37959. */
  37960. get: function () {
  37961. return this._imageProcessingConfiguration.colorGradingTexture;
  37962. },
  37963. /**
  37964. * Sets the Color Grading 2D Lookup Texture.
  37965. */
  37966. set: function (value) {
  37967. this._imageProcessingConfiguration.colorGradingTexture = value;
  37968. },
  37969. enumerable: true,
  37970. configurable: true
  37971. });
  37972. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37973. /**
  37974. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37975. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37976. * 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;
  37977. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37978. */
  37979. get: function () {
  37980. return this._imageProcessingConfiguration.colorCurves;
  37981. },
  37982. /**
  37983. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37984. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37985. * 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;
  37986. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37987. */
  37988. set: function (value) {
  37989. this._imageProcessingConfiguration.colorCurves = value;
  37990. },
  37991. enumerable: true,
  37992. configurable: true
  37993. });
  37994. PBRMaterial.prototype.getClassName = function () {
  37995. return "PBRMaterial";
  37996. };
  37997. PBRMaterial.prototype.getActiveTextures = function () {
  37998. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37999. if (this._albedoTexture) {
  38000. activeTextures.push(this._albedoTexture);
  38001. }
  38002. if (this._ambientTexture) {
  38003. activeTextures.push(this._ambientTexture);
  38004. }
  38005. if (this._opacityTexture) {
  38006. activeTextures.push(this._opacityTexture);
  38007. }
  38008. if (this._reflectionTexture) {
  38009. activeTextures.push(this._reflectionTexture);
  38010. }
  38011. if (this._emissiveTexture) {
  38012. activeTextures.push(this._emissiveTexture);
  38013. }
  38014. if (this._reflectivityTexture) {
  38015. activeTextures.push(this._reflectivityTexture);
  38016. }
  38017. if (this._metallicTexture) {
  38018. activeTextures.push(this._metallicTexture);
  38019. }
  38020. if (this._microSurfaceTexture) {
  38021. activeTextures.push(this._microSurfaceTexture);
  38022. }
  38023. if (this._bumpTexture) {
  38024. activeTextures.push(this._bumpTexture);
  38025. }
  38026. if (this._lightmapTexture) {
  38027. activeTextures.push(this._lightmapTexture);
  38028. }
  38029. if (this._refractionTexture) {
  38030. activeTextures.push(this._refractionTexture);
  38031. }
  38032. return activeTextures;
  38033. };
  38034. PBRMaterial.prototype.hasTexture = function (texture) {
  38035. if (_super.prototype.hasTexture.call(this, texture)) {
  38036. return true;
  38037. }
  38038. if (this._albedoTexture === texture) {
  38039. return true;
  38040. }
  38041. if (this._ambientTexture === texture) {
  38042. return true;
  38043. }
  38044. if (this._opacityTexture === texture) {
  38045. return true;
  38046. }
  38047. if (this._reflectionTexture === texture) {
  38048. return true;
  38049. }
  38050. if (this._reflectivityTexture === texture) {
  38051. return true;
  38052. }
  38053. if (this._metallicTexture === texture) {
  38054. return true;
  38055. }
  38056. if (this._microSurfaceTexture === texture) {
  38057. return true;
  38058. }
  38059. if (this._bumpTexture === texture) {
  38060. return true;
  38061. }
  38062. if (this._lightmapTexture === texture) {
  38063. return true;
  38064. }
  38065. if (this._refractionTexture === texture) {
  38066. return true;
  38067. }
  38068. return false;
  38069. };
  38070. PBRMaterial.prototype.clone = function (name) {
  38071. var _this = this;
  38072. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38073. clone.id = name;
  38074. clone.name = name;
  38075. return clone;
  38076. };
  38077. PBRMaterial.prototype.serialize = function () {
  38078. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38079. serializationObject.customType = "BABYLON.PBRMaterial";
  38080. return serializationObject;
  38081. };
  38082. // Statics
  38083. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38084. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38085. };
  38086. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38087. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38088. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38089. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38090. __decorate([
  38091. BABYLON.serialize(),
  38092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38093. ], PBRMaterial.prototype, "directIntensity", void 0);
  38094. __decorate([
  38095. BABYLON.serialize(),
  38096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38097. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38098. __decorate([
  38099. BABYLON.serialize(),
  38100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38101. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38102. __decorate([
  38103. BABYLON.serialize(),
  38104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38105. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38106. __decorate([
  38107. BABYLON.serialize(),
  38108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38109. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38110. __decorate([
  38111. BABYLON.serializeAsTexture(),
  38112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38113. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38114. __decorate([
  38115. BABYLON.serializeAsTexture(),
  38116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38117. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38118. __decorate([
  38119. BABYLON.serialize(),
  38120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38121. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38122. __decorate([
  38123. BABYLON.serializeAsTexture(),
  38124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38125. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38126. __decorate([
  38127. BABYLON.serializeAsTexture(),
  38128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38129. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38130. __decorate([
  38131. BABYLON.serializeAsTexture(),
  38132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38133. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38134. __decorate([
  38135. BABYLON.serializeAsTexture(),
  38136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38137. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38138. __decorate([
  38139. BABYLON.serializeAsTexture(),
  38140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38141. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38142. __decorate([
  38143. BABYLON.serialize(),
  38144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38145. ], PBRMaterial.prototype, "metallic", void 0);
  38146. __decorate([
  38147. BABYLON.serialize(),
  38148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38149. ], PBRMaterial.prototype, "roughness", void 0);
  38150. __decorate([
  38151. BABYLON.serializeAsTexture(),
  38152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38153. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38154. __decorate([
  38155. BABYLON.serializeAsTexture(),
  38156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38157. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38158. __decorate([
  38159. BABYLON.serializeAsTexture(),
  38160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38161. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38162. __decorate([
  38163. BABYLON.serializeAsTexture(),
  38164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38165. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38166. __decorate([
  38167. BABYLON.serializeAsColor3("ambient"),
  38168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38169. ], PBRMaterial.prototype, "ambientColor", void 0);
  38170. __decorate([
  38171. BABYLON.serializeAsColor3("albedo"),
  38172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38173. ], PBRMaterial.prototype, "albedoColor", void 0);
  38174. __decorate([
  38175. BABYLON.serializeAsColor3("reflectivity"),
  38176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38177. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38178. __decorate([
  38179. BABYLON.serializeAsColor3("reflection"),
  38180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38181. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38182. __decorate([
  38183. BABYLON.serializeAsColor3("emissive"),
  38184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38185. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38186. __decorate([
  38187. BABYLON.serialize(),
  38188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38189. ], PBRMaterial.prototype, "microSurface", void 0);
  38190. __decorate([
  38191. BABYLON.serialize(),
  38192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38193. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38194. __decorate([
  38195. BABYLON.serialize(),
  38196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38197. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38198. __decorate([
  38199. BABYLON.serialize(),
  38200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38201. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38202. __decorate([
  38203. BABYLON.serialize(),
  38204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38205. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38206. __decorate([
  38207. BABYLON.serialize(),
  38208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38209. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38210. __decorate([
  38211. BABYLON.serialize(),
  38212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38213. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38214. __decorate([
  38215. BABYLON.serialize(),
  38216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38217. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38218. __decorate([
  38219. BABYLON.serialize(),
  38220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38221. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38222. __decorate([
  38223. BABYLON.serialize(),
  38224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38225. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38226. __decorate([
  38227. BABYLON.serialize(),
  38228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38229. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38230. __decorate([
  38231. BABYLON.serialize(),
  38232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38233. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38234. __decorate([
  38235. BABYLON.serialize(),
  38236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38237. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38238. __decorate([
  38239. BABYLON.serialize(),
  38240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38241. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38242. __decorate([
  38243. BABYLON.serialize(),
  38244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38245. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38246. __decorate([
  38247. BABYLON.serialize(),
  38248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38249. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38250. __decorate([
  38251. BABYLON.serialize(),
  38252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38253. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38254. __decorate([
  38255. BABYLON.serialize(),
  38256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38257. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38258. __decorate([
  38259. BABYLON.serialize(),
  38260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38261. ], PBRMaterial.prototype, "useParallax", void 0);
  38262. __decorate([
  38263. BABYLON.serialize(),
  38264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38265. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38266. __decorate([
  38267. BABYLON.serialize(),
  38268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38269. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38270. __decorate([
  38271. BABYLON.serialize(),
  38272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38273. ], PBRMaterial.prototype, "disableLighting", void 0);
  38274. __decorate([
  38275. BABYLON.serialize(),
  38276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38277. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38278. __decorate([
  38279. BABYLON.serialize(),
  38280. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38281. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38282. __decorate([
  38283. BABYLON.serialize(),
  38284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38285. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38286. __decorate([
  38287. BABYLON.serialize(),
  38288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38289. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38290. __decorate([
  38291. BABYLON.serialize(),
  38292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38293. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38294. __decorate([
  38295. BABYLON.serialize(),
  38296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38297. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38298. __decorate([
  38299. BABYLON.serialize(),
  38300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38301. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38302. __decorate([
  38303. BABYLON.serializeAsTexture(),
  38304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38305. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38306. __decorate([
  38307. BABYLON.serialize(),
  38308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38309. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38310. __decorate([
  38311. BABYLON.serialize(),
  38312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38313. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38314. __decorate([
  38315. BABYLON.serialize(),
  38316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38317. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38318. return PBRMaterial;
  38319. }(BABYLON.PBRBaseMaterial));
  38320. BABYLON.PBRMaterial = PBRMaterial;
  38321. })(BABYLON || (BABYLON = {}));
  38322. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38323. var BABYLON;
  38324. (function (BABYLON) {
  38325. /**
  38326. * The PBR material of BJS following the metal roughness convention.
  38327. *
  38328. * This fits to the PBR convention in the GLTF definition:
  38329. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38330. */
  38331. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38332. __extends(PBRMetallicRoughnessMaterial, _super);
  38333. /**
  38334. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38335. *
  38336. * @param name The material name
  38337. * @param scene The scene the material will be use in.
  38338. */
  38339. function PBRMetallicRoughnessMaterial(name, scene) {
  38340. var _this = _super.call(this, name, scene) || this;
  38341. _this._useRoughnessFromMetallicTextureAlpha = false;
  38342. _this._useRoughnessFromMetallicTextureGreen = true;
  38343. _this._useMetallnessFromMetallicTextureBlue = true;
  38344. _this._forceMetallicWorkflow = true;
  38345. return _this;
  38346. }
  38347. /**
  38348. * Return the currrent class name of the material.
  38349. */
  38350. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38351. return "PBRMetallicRoughnessMaterial";
  38352. };
  38353. /**
  38354. * Return the active textures of the material.
  38355. */
  38356. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38357. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38358. if (this.baseTexture) {
  38359. activeTextures.push(this.baseTexture);
  38360. }
  38361. if (this.metallicRoughnessTexture) {
  38362. activeTextures.push(this.metallicRoughnessTexture);
  38363. }
  38364. return activeTextures;
  38365. };
  38366. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38367. if (_super.prototype.hasTexture.call(this, texture)) {
  38368. return true;
  38369. }
  38370. if (this.baseTexture === texture) {
  38371. return true;
  38372. }
  38373. if (this.metallicRoughnessTexture === texture) {
  38374. return true;
  38375. }
  38376. return false;
  38377. };
  38378. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38379. var _this = this;
  38380. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38381. clone.id = name;
  38382. clone.name = name;
  38383. return clone;
  38384. };
  38385. /**
  38386. * Serialize the material to a parsable JSON object.
  38387. */
  38388. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38389. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38390. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38391. return serializationObject;
  38392. };
  38393. /**
  38394. * Parses a JSON object correponding to the serialize function.
  38395. */
  38396. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38397. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38398. };
  38399. __decorate([
  38400. BABYLON.serializeAsColor3(),
  38401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38402. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38403. __decorate([
  38404. BABYLON.serializeAsTexture(),
  38405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38406. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38407. __decorate([
  38408. BABYLON.serialize(),
  38409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38410. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38411. __decorate([
  38412. BABYLON.serialize(),
  38413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38414. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38415. __decorate([
  38416. BABYLON.serializeAsTexture(),
  38417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38418. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38419. return PBRMetallicRoughnessMaterial;
  38420. }(BABYLON.PBRBaseSimpleMaterial));
  38421. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38422. })(BABYLON || (BABYLON = {}));
  38423. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38424. var BABYLON;
  38425. (function (BABYLON) {
  38426. /**
  38427. * The PBR material of BJS following the specular glossiness convention.
  38428. *
  38429. * This fits to the PBR convention in the GLTF definition:
  38430. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38431. */
  38432. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38433. __extends(PBRSpecularGlossinessMaterial, _super);
  38434. /**
  38435. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38436. *
  38437. * @param name The material name
  38438. * @param scene The scene the material will be use in.
  38439. */
  38440. function PBRSpecularGlossinessMaterial(name, scene) {
  38441. var _this = _super.call(this, name, scene) || this;
  38442. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38443. return _this;
  38444. }
  38445. /**
  38446. * Return the currrent class name of the material.
  38447. */
  38448. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38449. return "PBRSpecularGlossinessMaterial";
  38450. };
  38451. /**
  38452. * Return the active textures of the material.
  38453. */
  38454. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38455. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38456. if (this.diffuseTexture) {
  38457. activeTextures.push(this.diffuseTexture);
  38458. }
  38459. if (this.specularGlossinessTexture) {
  38460. activeTextures.push(this.specularGlossinessTexture);
  38461. }
  38462. return activeTextures;
  38463. };
  38464. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38465. if (_super.prototype.hasTexture.call(this, texture)) {
  38466. return true;
  38467. }
  38468. if (this.diffuseTexture === texture) {
  38469. return true;
  38470. }
  38471. if (this.specularGlossinessTexture === texture) {
  38472. return true;
  38473. }
  38474. return false;
  38475. };
  38476. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38477. var _this = this;
  38478. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38479. clone.id = name;
  38480. clone.name = name;
  38481. return clone;
  38482. };
  38483. /**
  38484. * Serialize the material to a parsable JSON object.
  38485. */
  38486. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38487. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38488. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38489. return serializationObject;
  38490. };
  38491. /**
  38492. * Parses a JSON object correponding to the serialize function.
  38493. */
  38494. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38495. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38496. };
  38497. __decorate([
  38498. BABYLON.serializeAsColor3("diffuse"),
  38499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38500. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38501. __decorate([
  38502. BABYLON.serializeAsTexture(),
  38503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38504. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38505. __decorate([
  38506. BABYLON.serializeAsColor3("specular"),
  38507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38508. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38509. __decorate([
  38510. BABYLON.serialize(),
  38511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38512. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38513. __decorate([
  38514. BABYLON.serializeAsTexture(),
  38515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38516. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38517. return PBRSpecularGlossinessMaterial;
  38518. }(BABYLON.PBRBaseSimpleMaterial));
  38519. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38520. })(BABYLON || (BABYLON = {}));
  38521. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38522. var BABYLON;
  38523. (function (BABYLON) {
  38524. BABYLON.CameraInputTypes = {};
  38525. var CameraInputsManager = /** @class */ (function () {
  38526. function CameraInputsManager(camera) {
  38527. this.attached = {};
  38528. this.camera = camera;
  38529. this.checkInputs = function () { };
  38530. }
  38531. CameraInputsManager.prototype.add = function (input) {
  38532. var type = input.getSimpleName();
  38533. if (this.attached[type]) {
  38534. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38535. return;
  38536. }
  38537. this.attached[type] = input;
  38538. input.camera = this.camera;
  38539. //for checkInputs, we are dynamically creating a function
  38540. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38541. if (input.checkInputs) {
  38542. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38543. }
  38544. if (this.attachedElement) {
  38545. input.attachControl(this.attachedElement);
  38546. }
  38547. };
  38548. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38549. for (var cam in this.attached) {
  38550. var input = this.attached[cam];
  38551. if (input === inputToRemove) {
  38552. input.detachControl(this.attachedElement);
  38553. input.camera = null;
  38554. delete this.attached[cam];
  38555. this.rebuildInputCheck();
  38556. }
  38557. }
  38558. };
  38559. CameraInputsManager.prototype.removeByType = function (inputType) {
  38560. for (var cam in this.attached) {
  38561. var input = this.attached[cam];
  38562. if (input.getClassName() === inputType) {
  38563. input.detachControl(this.attachedElement);
  38564. input.camera = null;
  38565. delete this.attached[cam];
  38566. this.rebuildInputCheck();
  38567. }
  38568. }
  38569. };
  38570. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38571. var current = this.checkInputs;
  38572. return function () {
  38573. current();
  38574. fn();
  38575. };
  38576. };
  38577. CameraInputsManager.prototype.attachInput = function (input) {
  38578. if (this.attachedElement) {
  38579. input.attachControl(this.attachedElement, this.noPreventDefault);
  38580. }
  38581. };
  38582. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38583. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38584. if (this.attachedElement) {
  38585. return;
  38586. }
  38587. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38588. this.attachedElement = element;
  38589. this.noPreventDefault = noPreventDefault;
  38590. for (var cam in this.attached) {
  38591. this.attached[cam].attachControl(element, noPreventDefault);
  38592. }
  38593. };
  38594. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38595. if (disconnect === void 0) { disconnect = false; }
  38596. if (this.attachedElement !== element) {
  38597. return;
  38598. }
  38599. for (var cam in this.attached) {
  38600. this.attached[cam].detachControl(element);
  38601. if (disconnect) {
  38602. this.attached[cam].camera = null;
  38603. }
  38604. }
  38605. this.attachedElement = null;
  38606. };
  38607. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38608. this.checkInputs = function () { };
  38609. for (var cam in this.attached) {
  38610. var input = this.attached[cam];
  38611. if (input.checkInputs) {
  38612. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38613. }
  38614. }
  38615. };
  38616. CameraInputsManager.prototype.clear = function () {
  38617. if (this.attachedElement) {
  38618. this.detachElement(this.attachedElement, true);
  38619. }
  38620. this.attached = {};
  38621. this.attachedElement = null;
  38622. this.checkInputs = function () { };
  38623. };
  38624. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38625. var inputs = {};
  38626. for (var cam in this.attached) {
  38627. var input = this.attached[cam];
  38628. var res = BABYLON.SerializationHelper.Serialize(input);
  38629. inputs[input.getClassName()] = res;
  38630. }
  38631. serializedCamera.inputsmgr = inputs;
  38632. };
  38633. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38634. var parsedInputs = parsedCamera.inputsmgr;
  38635. if (parsedInputs) {
  38636. this.clear();
  38637. for (var n in parsedInputs) {
  38638. var construct = BABYLON.CameraInputTypes[n];
  38639. if (construct) {
  38640. var parsedinput = parsedInputs[n];
  38641. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38642. this.add(input);
  38643. }
  38644. }
  38645. }
  38646. else {
  38647. //2016-03-08 this part is for managing backward compatibility
  38648. for (var n in this.attached) {
  38649. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38650. if (construct) {
  38651. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38652. this.remove(this.attached[n]);
  38653. this.add(input);
  38654. }
  38655. }
  38656. }
  38657. };
  38658. return CameraInputsManager;
  38659. }());
  38660. BABYLON.CameraInputsManager = CameraInputsManager;
  38661. })(BABYLON || (BABYLON = {}));
  38662. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38663. var BABYLON;
  38664. (function (BABYLON) {
  38665. var TargetCamera = /** @class */ (function (_super) {
  38666. __extends(TargetCamera, _super);
  38667. function TargetCamera(name, position, scene) {
  38668. var _this = _super.call(this, name, position, scene) || this;
  38669. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38670. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38671. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38672. _this.speed = 2.0;
  38673. _this.noRotationConstraint = false;
  38674. _this.lockedTarget = null;
  38675. _this._currentTarget = BABYLON.Vector3.Zero();
  38676. _this._viewMatrix = BABYLON.Matrix.Zero();
  38677. _this._camMatrix = BABYLON.Matrix.Zero();
  38678. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38679. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38680. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38681. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38682. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38683. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38684. _this._tempMatrix = BABYLON.Matrix.Zero();
  38685. return _this;
  38686. }
  38687. TargetCamera.prototype.getFrontPosition = function (distance) {
  38688. this.getWorldMatrix();
  38689. var direction = this.getTarget().subtract(this.position);
  38690. direction.normalize();
  38691. direction.scaleInPlace(distance);
  38692. return this.globalPosition.add(direction);
  38693. };
  38694. TargetCamera.prototype._getLockedTargetPosition = function () {
  38695. if (!this.lockedTarget) {
  38696. return null;
  38697. }
  38698. if (this.lockedTarget.absolutePosition) {
  38699. this.lockedTarget.computeWorldMatrix();
  38700. }
  38701. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38702. };
  38703. TargetCamera.prototype.storeState = function () {
  38704. this._storedPosition = this.position.clone();
  38705. this._storedRotation = this.rotation.clone();
  38706. if (this.rotationQuaternion) {
  38707. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38708. }
  38709. return _super.prototype.storeState.call(this);
  38710. };
  38711. /**
  38712. * Restored camera state. You must call storeState() first
  38713. */
  38714. TargetCamera.prototype._restoreStateValues = function () {
  38715. if (!_super.prototype._restoreStateValues.call(this)) {
  38716. return false;
  38717. }
  38718. this.position = this._storedPosition.clone();
  38719. this.rotation = this._storedRotation.clone();
  38720. if (this.rotationQuaternion) {
  38721. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38722. }
  38723. this.cameraDirection.copyFromFloats(0, 0, 0);
  38724. this.cameraRotation.copyFromFloats(0, 0);
  38725. return true;
  38726. };
  38727. // Cache
  38728. TargetCamera.prototype._initCache = function () {
  38729. _super.prototype._initCache.call(this);
  38730. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38731. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38732. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38733. };
  38734. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38735. if (!ignoreParentClass) {
  38736. _super.prototype._updateCache.call(this);
  38737. }
  38738. var lockedTargetPosition = this._getLockedTargetPosition();
  38739. if (!lockedTargetPosition) {
  38740. this._cache.lockedTarget = null;
  38741. }
  38742. else {
  38743. if (!this._cache.lockedTarget) {
  38744. this._cache.lockedTarget = lockedTargetPosition.clone();
  38745. }
  38746. else {
  38747. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38748. }
  38749. }
  38750. this._cache.rotation.copyFrom(this.rotation);
  38751. if (this.rotationQuaternion)
  38752. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38753. };
  38754. // Synchronized
  38755. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38756. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38757. return false;
  38758. }
  38759. var lockedTargetPosition = this._getLockedTargetPosition();
  38760. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38761. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38762. };
  38763. // Methods
  38764. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38765. var engine = this.getEngine();
  38766. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38767. };
  38768. // Target
  38769. TargetCamera.prototype.setTarget = function (target) {
  38770. this.upVector.normalize();
  38771. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38772. this._camMatrix.invert();
  38773. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38774. var vDir = target.subtract(this.position);
  38775. if (vDir.x >= 0.0) {
  38776. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38777. }
  38778. else {
  38779. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38780. }
  38781. this.rotation.z = 0;
  38782. if (isNaN(this.rotation.x)) {
  38783. this.rotation.x = 0;
  38784. }
  38785. if (isNaN(this.rotation.y)) {
  38786. this.rotation.y = 0;
  38787. }
  38788. if (isNaN(this.rotation.z)) {
  38789. this.rotation.z = 0;
  38790. }
  38791. if (this.rotationQuaternion) {
  38792. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38793. }
  38794. };
  38795. /**
  38796. * Return the current target position of the camera. This value is expressed in local space.
  38797. */
  38798. TargetCamera.prototype.getTarget = function () {
  38799. return this._currentTarget;
  38800. };
  38801. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38802. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38803. };
  38804. TargetCamera.prototype._updatePosition = function () {
  38805. if (this.parent) {
  38806. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38807. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38808. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38809. return;
  38810. }
  38811. this.position.addInPlace(this.cameraDirection);
  38812. };
  38813. TargetCamera.prototype._checkInputs = function () {
  38814. var needToMove = this._decideIfNeedsToMove();
  38815. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38816. // Move
  38817. if (needToMove) {
  38818. this._updatePosition();
  38819. }
  38820. // Rotate
  38821. if (needToRotate) {
  38822. this.rotation.x += this.cameraRotation.x;
  38823. this.rotation.y += this.cameraRotation.y;
  38824. //rotate, if quaternion is set and rotation was used
  38825. if (this.rotationQuaternion) {
  38826. var len = this.rotation.lengthSquared();
  38827. if (len) {
  38828. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38829. }
  38830. }
  38831. if (!this.noRotationConstraint) {
  38832. var limit = (Math.PI / 2) * 0.95;
  38833. if (this.rotation.x > limit)
  38834. this.rotation.x = limit;
  38835. if (this.rotation.x < -limit)
  38836. this.rotation.x = -limit;
  38837. }
  38838. }
  38839. // Inertia
  38840. if (needToMove) {
  38841. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38842. this.cameraDirection.x = 0;
  38843. }
  38844. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38845. this.cameraDirection.y = 0;
  38846. }
  38847. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38848. this.cameraDirection.z = 0;
  38849. }
  38850. this.cameraDirection.scaleInPlace(this.inertia);
  38851. }
  38852. if (needToRotate) {
  38853. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38854. this.cameraRotation.x = 0;
  38855. }
  38856. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38857. this.cameraRotation.y = 0;
  38858. }
  38859. this.cameraRotation.scaleInPlace(this.inertia);
  38860. }
  38861. _super.prototype._checkInputs.call(this);
  38862. };
  38863. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38864. if (this.rotationQuaternion) {
  38865. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38866. }
  38867. else {
  38868. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38869. }
  38870. //update the up vector!
  38871. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  38872. };
  38873. TargetCamera.prototype._getViewMatrix = function () {
  38874. if (this.lockedTarget) {
  38875. this.setTarget(this._getLockedTargetPosition());
  38876. }
  38877. // Compute
  38878. this._updateCameraRotationMatrix();
  38879. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38880. // Computing target and final matrix
  38881. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38882. if (this.getScene().useRightHandedSystem) {
  38883. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38884. }
  38885. else {
  38886. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38887. }
  38888. return this._viewMatrix;
  38889. };
  38890. /**
  38891. * @override
  38892. * Override Camera.createRigCamera
  38893. */
  38894. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38895. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38896. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38897. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38898. if (!this.rotationQuaternion) {
  38899. this.rotationQuaternion = new BABYLON.Quaternion();
  38900. }
  38901. rigCamera._cameraRigParams = {};
  38902. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38903. }
  38904. return rigCamera;
  38905. }
  38906. return null;
  38907. };
  38908. /**
  38909. * @override
  38910. * Override Camera._updateRigCameras
  38911. */
  38912. TargetCamera.prototype._updateRigCameras = function () {
  38913. var camLeft = this._rigCameras[0];
  38914. var camRight = this._rigCameras[1];
  38915. switch (this.cameraRigMode) {
  38916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38920. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38921. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38922. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38923. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38924. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38925. camLeft.setTarget(this.getTarget());
  38926. camRight.setTarget(this.getTarget());
  38927. break;
  38928. case BABYLON.Camera.RIG_MODE_VR:
  38929. if (camLeft.rotationQuaternion) {
  38930. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38931. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38932. }
  38933. else {
  38934. camLeft.rotation.copyFrom(this.rotation);
  38935. camRight.rotation.copyFrom(this.rotation);
  38936. }
  38937. camLeft.position.copyFrom(this.position);
  38938. camRight.position.copyFrom(this.position);
  38939. break;
  38940. }
  38941. _super.prototype._updateRigCameras.call(this);
  38942. };
  38943. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38944. if (!this._rigCamTransformMatrix) {
  38945. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38946. }
  38947. var target = this.getTarget();
  38948. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38949. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38950. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38951. };
  38952. TargetCamera.prototype.getClassName = function () {
  38953. return "TargetCamera";
  38954. };
  38955. __decorate([
  38956. BABYLON.serializeAsVector3()
  38957. ], TargetCamera.prototype, "rotation", void 0);
  38958. __decorate([
  38959. BABYLON.serialize()
  38960. ], TargetCamera.prototype, "speed", void 0);
  38961. __decorate([
  38962. BABYLON.serializeAsMeshReference("lockedTargetId")
  38963. ], TargetCamera.prototype, "lockedTarget", void 0);
  38964. return TargetCamera;
  38965. }(BABYLON.Camera));
  38966. BABYLON.TargetCamera = TargetCamera;
  38967. })(BABYLON || (BABYLON = {}));
  38968. //# sourceMappingURL=babylon.targetCamera.js.map
  38969. var BABYLON;
  38970. (function (BABYLON) {
  38971. var FreeCameraMouseInput = /** @class */ (function () {
  38972. function FreeCameraMouseInput(touchEnabled) {
  38973. if (touchEnabled === void 0) { touchEnabled = true; }
  38974. this.touchEnabled = touchEnabled;
  38975. this.buttons = [0, 1, 2];
  38976. this.angularSensibility = 2000.0;
  38977. this.previousPosition = null;
  38978. }
  38979. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38980. var _this = this;
  38981. var engine = this.camera.getEngine();
  38982. if (!this._pointerInput) {
  38983. this._pointerInput = function (p, s) {
  38984. var evt = p.event;
  38985. if (engine.isInVRExclusivePointerMode) {
  38986. return;
  38987. }
  38988. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38989. return;
  38990. }
  38991. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38992. return;
  38993. }
  38994. var srcElement = (evt.srcElement || evt.target);
  38995. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38996. try {
  38997. srcElement.setPointerCapture(evt.pointerId);
  38998. }
  38999. catch (e) {
  39000. //Nothing to do with the error. Execution will continue.
  39001. }
  39002. _this.previousPosition = {
  39003. x: evt.clientX,
  39004. y: evt.clientY
  39005. };
  39006. if (!noPreventDefault) {
  39007. evt.preventDefault();
  39008. element.focus();
  39009. }
  39010. }
  39011. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39012. try {
  39013. srcElement.releasePointerCapture(evt.pointerId);
  39014. }
  39015. catch (e) {
  39016. //Nothing to do with the error.
  39017. }
  39018. _this.previousPosition = null;
  39019. if (!noPreventDefault) {
  39020. evt.preventDefault();
  39021. }
  39022. }
  39023. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39024. if (!_this.previousPosition || engine.isPointerLock) {
  39025. return;
  39026. }
  39027. var offsetX = evt.clientX - _this.previousPosition.x;
  39028. var offsetY = evt.clientY - _this.previousPosition.y;
  39029. if (_this.camera.getScene().useRightHandedSystem) {
  39030. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39031. }
  39032. else {
  39033. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39034. }
  39035. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39036. _this.previousPosition = {
  39037. x: evt.clientX,
  39038. y: evt.clientY
  39039. };
  39040. if (!noPreventDefault) {
  39041. evt.preventDefault();
  39042. }
  39043. }
  39044. };
  39045. }
  39046. this._onMouseMove = function (evt) {
  39047. if (!engine.isPointerLock) {
  39048. return;
  39049. }
  39050. if (engine.isInVRExclusivePointerMode) {
  39051. return;
  39052. }
  39053. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39054. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39055. if (_this.camera.getScene().useRightHandedSystem) {
  39056. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39057. }
  39058. else {
  39059. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39060. }
  39061. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39062. _this.previousPosition = null;
  39063. if (!noPreventDefault) {
  39064. evt.preventDefault();
  39065. }
  39066. };
  39067. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39068. element.addEventListener("mousemove", this._onMouseMove, false);
  39069. };
  39070. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39071. if (this._observer && element) {
  39072. this.camera.getScene().onPointerObservable.remove(this._observer);
  39073. if (this._onMouseMove) {
  39074. element.removeEventListener("mousemove", this._onMouseMove);
  39075. }
  39076. this._observer = null;
  39077. this._onMouseMove = null;
  39078. this.previousPosition = null;
  39079. }
  39080. };
  39081. FreeCameraMouseInput.prototype.getClassName = function () {
  39082. return "FreeCameraMouseInput";
  39083. };
  39084. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39085. return "mouse";
  39086. };
  39087. __decorate([
  39088. BABYLON.serialize()
  39089. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39090. __decorate([
  39091. BABYLON.serialize()
  39092. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39093. return FreeCameraMouseInput;
  39094. }());
  39095. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39096. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39097. })(BABYLON || (BABYLON = {}));
  39098. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39099. var BABYLON;
  39100. (function (BABYLON) {
  39101. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39102. function FreeCameraKeyboardMoveInput() {
  39103. this._keys = new Array();
  39104. this.keysUp = [38];
  39105. this.keysDown = [40];
  39106. this.keysLeft = [37];
  39107. this.keysRight = [39];
  39108. }
  39109. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39110. var _this = this;
  39111. if (this._onCanvasBlurObserver) {
  39112. return;
  39113. }
  39114. this._scene = this.camera.getScene();
  39115. this._engine = this._scene.getEngine();
  39116. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39117. _this._keys = [];
  39118. });
  39119. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39120. var evt = info.event;
  39121. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39122. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39123. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39124. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39125. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39126. var index = _this._keys.indexOf(evt.keyCode);
  39127. if (index === -1) {
  39128. _this._keys.push(evt.keyCode);
  39129. }
  39130. if (!noPreventDefault) {
  39131. evt.preventDefault();
  39132. }
  39133. }
  39134. }
  39135. else {
  39136. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39137. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39138. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39139. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39140. var index = _this._keys.indexOf(evt.keyCode);
  39141. if (index >= 0) {
  39142. _this._keys.splice(index, 1);
  39143. }
  39144. if (!noPreventDefault) {
  39145. evt.preventDefault();
  39146. }
  39147. }
  39148. }
  39149. });
  39150. };
  39151. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39152. if (this._scene) {
  39153. if (this._onKeyboardObserver) {
  39154. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39155. }
  39156. if (this._onCanvasBlurObserver) {
  39157. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39158. }
  39159. this._onKeyboardObserver = null;
  39160. this._onCanvasBlurObserver = null;
  39161. }
  39162. this._keys = [];
  39163. };
  39164. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39165. if (this._onKeyboardObserver) {
  39166. var camera = this.camera;
  39167. // Keyboard
  39168. for (var index = 0; index < this._keys.length; index++) {
  39169. var keyCode = this._keys[index];
  39170. var speed = camera._computeLocalCameraSpeed();
  39171. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39172. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39173. }
  39174. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39175. camera._localDirection.copyFromFloats(0, 0, speed);
  39176. }
  39177. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39178. camera._localDirection.copyFromFloats(speed, 0, 0);
  39179. }
  39180. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39181. camera._localDirection.copyFromFloats(0, 0, -speed);
  39182. }
  39183. if (camera.getScene().useRightHandedSystem) {
  39184. camera._localDirection.z *= -1;
  39185. }
  39186. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39187. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39188. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39189. }
  39190. }
  39191. };
  39192. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39193. return "FreeCameraKeyboardMoveInput";
  39194. };
  39195. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39196. this._keys = [];
  39197. };
  39198. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39199. return "keyboard";
  39200. };
  39201. __decorate([
  39202. BABYLON.serialize()
  39203. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39204. __decorate([
  39205. BABYLON.serialize()
  39206. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39207. __decorate([
  39208. BABYLON.serialize()
  39209. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39210. __decorate([
  39211. BABYLON.serialize()
  39212. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39213. return FreeCameraKeyboardMoveInput;
  39214. }());
  39215. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39216. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39217. })(BABYLON || (BABYLON = {}));
  39218. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39219. var BABYLON;
  39220. (function (BABYLON) {
  39221. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39222. __extends(FreeCameraInputsManager, _super);
  39223. function FreeCameraInputsManager(camera) {
  39224. return _super.call(this, camera) || this;
  39225. }
  39226. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39227. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39228. return this;
  39229. };
  39230. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39231. if (touchEnabled === void 0) { touchEnabled = true; }
  39232. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39233. return this;
  39234. };
  39235. FreeCameraInputsManager.prototype.addGamepad = function () {
  39236. this.add(new BABYLON.FreeCameraGamepadInput());
  39237. return this;
  39238. };
  39239. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39240. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39241. return this;
  39242. };
  39243. FreeCameraInputsManager.prototype.addTouch = function () {
  39244. this.add(new BABYLON.FreeCameraTouchInput());
  39245. return this;
  39246. };
  39247. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39248. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39249. return this;
  39250. };
  39251. return FreeCameraInputsManager;
  39252. }(BABYLON.CameraInputsManager));
  39253. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39254. })(BABYLON || (BABYLON = {}));
  39255. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39256. var BABYLON;
  39257. (function (BABYLON) {
  39258. var FreeCamera = /** @class */ (function (_super) {
  39259. __extends(FreeCamera, _super);
  39260. function FreeCamera(name, position, scene) {
  39261. var _this = _super.call(this, name, position, scene) || this;
  39262. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39263. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39264. _this.checkCollisions = false;
  39265. _this.applyGravity = false;
  39266. _this._needMoveForGravity = false;
  39267. _this._oldPosition = BABYLON.Vector3.Zero();
  39268. _this._diffPosition = BABYLON.Vector3.Zero();
  39269. _this._newPosition = BABYLON.Vector3.Zero();
  39270. // Collisions
  39271. _this._collisionMask = -1;
  39272. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39273. if (collidedMesh === void 0) { collidedMesh = null; }
  39274. //TODO move this to the collision coordinator!
  39275. if (_this.getScene().workerCollisions)
  39276. newPosition.multiplyInPlace(_this._collider._radius);
  39277. var updatePosition = function (newPos) {
  39278. _this._newPosition.copyFrom(newPos);
  39279. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39280. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39281. _this.position.addInPlace(_this._diffPosition);
  39282. if (_this.onCollide && collidedMesh) {
  39283. _this.onCollide(collidedMesh);
  39284. }
  39285. }
  39286. };
  39287. updatePosition(newPosition);
  39288. };
  39289. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39290. _this.inputs.addKeyboard().addMouse();
  39291. return _this;
  39292. }
  39293. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39294. //-- begin properties for backward compatibility for inputs
  39295. get: function () {
  39296. var mouse = this.inputs.attached["mouse"];
  39297. if (mouse)
  39298. return mouse.angularSensibility;
  39299. return 0;
  39300. },
  39301. set: function (value) {
  39302. var mouse = this.inputs.attached["mouse"];
  39303. if (mouse)
  39304. mouse.angularSensibility = value;
  39305. },
  39306. enumerable: true,
  39307. configurable: true
  39308. });
  39309. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39310. get: function () {
  39311. var keyboard = this.inputs.attached["keyboard"];
  39312. if (keyboard)
  39313. return keyboard.keysUp;
  39314. return [];
  39315. },
  39316. set: function (value) {
  39317. var keyboard = this.inputs.attached["keyboard"];
  39318. if (keyboard)
  39319. keyboard.keysUp = value;
  39320. },
  39321. enumerable: true,
  39322. configurable: true
  39323. });
  39324. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39325. get: function () {
  39326. var keyboard = this.inputs.attached["keyboard"];
  39327. if (keyboard)
  39328. return keyboard.keysDown;
  39329. return [];
  39330. },
  39331. set: function (value) {
  39332. var keyboard = this.inputs.attached["keyboard"];
  39333. if (keyboard)
  39334. keyboard.keysDown = value;
  39335. },
  39336. enumerable: true,
  39337. configurable: true
  39338. });
  39339. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39340. get: function () {
  39341. var keyboard = this.inputs.attached["keyboard"];
  39342. if (keyboard)
  39343. return keyboard.keysLeft;
  39344. return [];
  39345. },
  39346. set: function (value) {
  39347. var keyboard = this.inputs.attached["keyboard"];
  39348. if (keyboard)
  39349. keyboard.keysLeft = value;
  39350. },
  39351. enumerable: true,
  39352. configurable: true
  39353. });
  39354. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39355. get: function () {
  39356. var keyboard = this.inputs.attached["keyboard"];
  39357. if (keyboard)
  39358. return keyboard.keysRight;
  39359. return [];
  39360. },
  39361. set: function (value) {
  39362. var keyboard = this.inputs.attached["keyboard"];
  39363. if (keyboard)
  39364. keyboard.keysRight = value;
  39365. },
  39366. enumerable: true,
  39367. configurable: true
  39368. });
  39369. // Controls
  39370. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39371. this.inputs.attachElement(element, noPreventDefault);
  39372. };
  39373. FreeCamera.prototype.detachControl = function (element) {
  39374. this.inputs.detachElement(element);
  39375. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39376. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39377. };
  39378. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39379. get: function () {
  39380. return this._collisionMask;
  39381. },
  39382. set: function (mask) {
  39383. this._collisionMask = !isNaN(mask) ? mask : -1;
  39384. },
  39385. enumerable: true,
  39386. configurable: true
  39387. });
  39388. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39389. var globalPosition;
  39390. if (this.parent) {
  39391. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39392. }
  39393. else {
  39394. globalPosition = this.position;
  39395. }
  39396. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39397. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39398. if (!this._collider) {
  39399. this._collider = new BABYLON.Collider();
  39400. }
  39401. this._collider._radius = this.ellipsoid;
  39402. this._collider.collisionMask = this._collisionMask;
  39403. //no need for clone, as long as gravity is not on.
  39404. var actualDisplacement = displacement;
  39405. //add gravity to the direction to prevent the dual-collision checking
  39406. if (this.applyGravity) {
  39407. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39408. actualDisplacement = displacement.add(this.getScene().gravity);
  39409. }
  39410. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39411. };
  39412. FreeCamera.prototype._checkInputs = function () {
  39413. if (!this._localDirection) {
  39414. this._localDirection = BABYLON.Vector3.Zero();
  39415. this._transformedDirection = BABYLON.Vector3.Zero();
  39416. }
  39417. this.inputs.checkInputs();
  39418. _super.prototype._checkInputs.call(this);
  39419. };
  39420. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39421. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39422. };
  39423. FreeCamera.prototype._updatePosition = function () {
  39424. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39425. this._collideWithWorld(this.cameraDirection);
  39426. }
  39427. else {
  39428. _super.prototype._updatePosition.call(this);
  39429. }
  39430. };
  39431. FreeCamera.prototype.dispose = function () {
  39432. this.inputs.clear();
  39433. _super.prototype.dispose.call(this);
  39434. };
  39435. FreeCamera.prototype.getClassName = function () {
  39436. return "FreeCamera";
  39437. };
  39438. __decorate([
  39439. BABYLON.serializeAsVector3()
  39440. ], FreeCamera.prototype, "ellipsoid", void 0);
  39441. __decorate([
  39442. BABYLON.serializeAsVector3()
  39443. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39444. __decorate([
  39445. BABYLON.serialize()
  39446. ], FreeCamera.prototype, "checkCollisions", void 0);
  39447. __decorate([
  39448. BABYLON.serialize()
  39449. ], FreeCamera.prototype, "applyGravity", void 0);
  39450. return FreeCamera;
  39451. }(BABYLON.TargetCamera));
  39452. BABYLON.FreeCamera = FreeCamera;
  39453. })(BABYLON || (BABYLON = {}));
  39454. //# sourceMappingURL=babylon.freeCamera.js.map
  39455. var BABYLON;
  39456. (function (BABYLON) {
  39457. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39458. function ArcRotateCameraKeyboardMoveInput() {
  39459. this._keys = new Array();
  39460. this.keysUp = [38];
  39461. this.keysDown = [40];
  39462. this.keysLeft = [37];
  39463. this.keysRight = [39];
  39464. this.keysReset = [220];
  39465. this.panningSensibility = 50.0;
  39466. this.zoomingSensibility = 25.0;
  39467. this.useAltToZoom = true;
  39468. }
  39469. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39470. var _this = this;
  39471. if (this._onCanvasBlurObserver) {
  39472. return;
  39473. }
  39474. this._scene = this.camera.getScene();
  39475. this._engine = this._scene.getEngine();
  39476. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39477. _this._keys = [];
  39478. });
  39479. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39480. var evt = info.event;
  39481. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39482. _this._ctrlPressed = evt.ctrlKey;
  39483. _this._altPressed = evt.altKey;
  39484. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39485. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39486. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39487. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39488. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39489. var index = _this._keys.indexOf(evt.keyCode);
  39490. if (index === -1) {
  39491. _this._keys.push(evt.keyCode);
  39492. }
  39493. if (evt.preventDefault) {
  39494. if (!noPreventDefault) {
  39495. evt.preventDefault();
  39496. }
  39497. }
  39498. }
  39499. }
  39500. else {
  39501. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39502. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39503. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39504. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39505. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39506. var index = _this._keys.indexOf(evt.keyCode);
  39507. if (index >= 0) {
  39508. _this._keys.splice(index, 1);
  39509. }
  39510. if (evt.preventDefault) {
  39511. if (!noPreventDefault) {
  39512. evt.preventDefault();
  39513. }
  39514. }
  39515. }
  39516. }
  39517. });
  39518. };
  39519. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39520. if (this._scene) {
  39521. if (this._onKeyboardObserver) {
  39522. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39523. }
  39524. if (this._onCanvasBlurObserver) {
  39525. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39526. }
  39527. this._onKeyboardObserver = null;
  39528. this._onCanvasBlurObserver = null;
  39529. }
  39530. this._keys = [];
  39531. };
  39532. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39533. if (this._onKeyboardObserver) {
  39534. var camera = this.camera;
  39535. for (var index = 0; index < this._keys.length; index++) {
  39536. var keyCode = this._keys[index];
  39537. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39538. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39539. camera.inertialPanningX -= 1 / this.panningSensibility;
  39540. }
  39541. else {
  39542. camera.inertialAlphaOffset -= 0.01;
  39543. }
  39544. }
  39545. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39546. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39547. camera.inertialPanningY += 1 / this.panningSensibility;
  39548. }
  39549. else if (this._altPressed && this.useAltToZoom) {
  39550. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39551. }
  39552. else {
  39553. camera.inertialBetaOffset -= 0.01;
  39554. }
  39555. }
  39556. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39557. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39558. camera.inertialPanningX += 1 / this.panningSensibility;
  39559. }
  39560. else {
  39561. camera.inertialAlphaOffset += 0.01;
  39562. }
  39563. }
  39564. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39565. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39566. camera.inertialPanningY -= 1 / this.panningSensibility;
  39567. }
  39568. else if (this._altPressed && this.useAltToZoom) {
  39569. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39570. }
  39571. else {
  39572. camera.inertialBetaOffset += 0.01;
  39573. }
  39574. }
  39575. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39576. camera.restoreState();
  39577. }
  39578. }
  39579. }
  39580. };
  39581. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39582. return "ArcRotateCameraKeyboardMoveInput";
  39583. };
  39584. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39585. return "keyboard";
  39586. };
  39587. __decorate([
  39588. BABYLON.serialize()
  39589. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39590. __decorate([
  39591. BABYLON.serialize()
  39592. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39593. __decorate([
  39594. BABYLON.serialize()
  39595. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39596. __decorate([
  39597. BABYLON.serialize()
  39598. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39599. __decorate([
  39600. BABYLON.serialize()
  39601. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39602. __decorate([
  39603. BABYLON.serialize()
  39604. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39605. __decorate([
  39606. BABYLON.serialize()
  39607. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39608. __decorate([
  39609. BABYLON.serialize()
  39610. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39611. return ArcRotateCameraKeyboardMoveInput;
  39612. }());
  39613. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39614. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39615. })(BABYLON || (BABYLON = {}));
  39616. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39617. var BABYLON;
  39618. (function (BABYLON) {
  39619. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39620. function ArcRotateCameraMouseWheelInput() {
  39621. this.wheelPrecision = 3.0;
  39622. /**
  39623. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39624. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39625. */
  39626. this.wheelDeltaPercentage = 0;
  39627. }
  39628. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39629. var _this = this;
  39630. this._wheel = function (p, s) {
  39631. //sanity check - this should be a PointerWheel event.
  39632. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39633. return;
  39634. var event = p.event;
  39635. var delta = 0;
  39636. if (event.wheelDelta) {
  39637. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39638. }
  39639. else if (event.detail) {
  39640. delta = -event.detail / _this.wheelPrecision;
  39641. }
  39642. if (delta)
  39643. _this.camera.inertialRadiusOffset += delta;
  39644. if (event.preventDefault) {
  39645. if (!noPreventDefault) {
  39646. event.preventDefault();
  39647. }
  39648. }
  39649. };
  39650. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39651. };
  39652. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39653. if (this._observer && element) {
  39654. this.camera.getScene().onPointerObservable.remove(this._observer);
  39655. this._observer = null;
  39656. this._wheel = null;
  39657. }
  39658. };
  39659. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39660. return "ArcRotateCameraMouseWheelInput";
  39661. };
  39662. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39663. return "mousewheel";
  39664. };
  39665. __decorate([
  39666. BABYLON.serialize()
  39667. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39668. __decorate([
  39669. BABYLON.serialize()
  39670. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39671. return ArcRotateCameraMouseWheelInput;
  39672. }());
  39673. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39674. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39675. })(BABYLON || (BABYLON = {}));
  39676. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39677. var BABYLON;
  39678. (function (BABYLON) {
  39679. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39680. function ArcRotateCameraPointersInput() {
  39681. this.buttons = [0, 1, 2];
  39682. this.angularSensibilityX = 1000.0;
  39683. this.angularSensibilityY = 1000.0;
  39684. this.pinchPrecision = 12.0;
  39685. /**
  39686. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39687. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39688. */
  39689. this.pinchDeltaPercentage = 0;
  39690. this.panningSensibility = 1000.0;
  39691. this.multiTouchPanning = true;
  39692. this.multiTouchPanAndZoom = true;
  39693. this._isPanClick = false;
  39694. this.pinchInwards = true;
  39695. }
  39696. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39697. var _this = this;
  39698. var engine = this.camera.getEngine();
  39699. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39700. var pointA = null;
  39701. var pointB = null;
  39702. var previousPinchSquaredDistance = 0;
  39703. var initialDistance = 0;
  39704. var twoFingerActivityCount = 0;
  39705. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39706. this._pointerInput = function (p, s) {
  39707. var evt = p.event;
  39708. var isTouch = p.event.pointerType === "touch";
  39709. if (engine.isInVRExclusivePointerMode) {
  39710. return;
  39711. }
  39712. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39713. return;
  39714. }
  39715. var srcElement = (evt.srcElement || evt.target);
  39716. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39717. try {
  39718. srcElement.setPointerCapture(evt.pointerId);
  39719. }
  39720. catch (e) {
  39721. //Nothing to do with the error. Execution will continue.
  39722. }
  39723. // Manage panning with pan button click
  39724. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39725. // manage pointers
  39726. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39727. if (pointA === null) {
  39728. pointA = cacheSoloPointer;
  39729. }
  39730. else if (pointB === null) {
  39731. pointB = cacheSoloPointer;
  39732. }
  39733. if (!noPreventDefault) {
  39734. evt.preventDefault();
  39735. element.focus();
  39736. }
  39737. }
  39738. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39739. _this.camera.restoreState();
  39740. }
  39741. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39742. try {
  39743. srcElement.releasePointerCapture(evt.pointerId);
  39744. }
  39745. catch (e) {
  39746. //Nothing to do with the error.
  39747. }
  39748. cacheSoloPointer = null;
  39749. previousPinchSquaredDistance = 0;
  39750. previousMultiTouchPanPosition.isPaning = false;
  39751. previousMultiTouchPanPosition.isPinching = false;
  39752. twoFingerActivityCount = 0;
  39753. initialDistance = 0;
  39754. if (!isTouch) {
  39755. pointB = null; // Mouse and pen are mono pointer
  39756. }
  39757. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39758. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39759. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39760. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39761. if (engine.badOS) {
  39762. pointA = pointB = null;
  39763. }
  39764. else {
  39765. //only remove the impacted pointer in case of multitouch allowing on most
  39766. //platforms switching from rotate to zoom and pan seamlessly.
  39767. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39768. pointA = pointB;
  39769. pointB = null;
  39770. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39771. }
  39772. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39773. pointB = null;
  39774. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39775. }
  39776. else {
  39777. pointA = pointB = null;
  39778. }
  39779. }
  39780. if (!noPreventDefault) {
  39781. evt.preventDefault();
  39782. }
  39783. }
  39784. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39785. if (!noPreventDefault) {
  39786. evt.preventDefault();
  39787. }
  39788. // One button down
  39789. if (pointA && pointB === null && cacheSoloPointer) {
  39790. if (_this.panningSensibility !== 0 &&
  39791. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39792. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39793. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39794. }
  39795. else {
  39796. var offsetX = evt.clientX - cacheSoloPointer.x;
  39797. var offsetY = evt.clientY - cacheSoloPointer.y;
  39798. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39799. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39800. }
  39801. cacheSoloPointer.x = evt.clientX;
  39802. cacheSoloPointer.y = evt.clientY;
  39803. }
  39804. else if (pointA && pointB) {
  39805. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39806. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39807. ed.x = evt.clientX;
  39808. ed.y = evt.clientY;
  39809. var direction = _this.pinchInwards ? 1 : -1;
  39810. var distX = pointA.x - pointB.x;
  39811. var distY = pointA.y - pointB.y;
  39812. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39813. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39814. if (previousPinchSquaredDistance === 0) {
  39815. initialDistance = pinchDistance;
  39816. previousPinchSquaredDistance = pinchSquaredDistance;
  39817. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39818. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39819. return;
  39820. }
  39821. if (_this.multiTouchPanAndZoom) {
  39822. if (_this.pinchDeltaPercentage) {
  39823. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39824. }
  39825. else {
  39826. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39827. (_this.pinchPrecision *
  39828. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39829. direction);
  39830. }
  39831. if (_this.panningSensibility !== 0) {
  39832. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39833. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39834. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39835. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39836. previousMultiTouchPanPosition.x = pointersCenterX;
  39837. previousMultiTouchPanPosition.y = pointersCenterY;
  39838. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39839. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39840. }
  39841. }
  39842. else {
  39843. twoFingerActivityCount++;
  39844. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39845. if (_this.pinchDeltaPercentage) {
  39846. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39847. }
  39848. else {
  39849. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39850. (_this.pinchPrecision *
  39851. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39852. direction);
  39853. }
  39854. previousMultiTouchPanPosition.isPaning = false;
  39855. previousMultiTouchPanPosition.isPinching = true;
  39856. }
  39857. else {
  39858. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39859. if (!previousMultiTouchPanPosition.isPaning) {
  39860. previousMultiTouchPanPosition.isPaning = true;
  39861. previousMultiTouchPanPosition.isPinching = false;
  39862. previousMultiTouchPanPosition.x = ed.x;
  39863. previousMultiTouchPanPosition.y = ed.y;
  39864. return;
  39865. }
  39866. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39867. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39868. }
  39869. }
  39870. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39871. previousMultiTouchPanPosition.x = ed.x;
  39872. previousMultiTouchPanPosition.y = ed.y;
  39873. }
  39874. }
  39875. previousPinchSquaredDistance = pinchSquaredDistance;
  39876. }
  39877. }
  39878. };
  39879. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39880. this._onContextMenu = function (evt) {
  39881. evt.preventDefault();
  39882. };
  39883. if (!this.camera._useCtrlForPanning) {
  39884. element.addEventListener("contextmenu", this._onContextMenu, false);
  39885. }
  39886. this._onLostFocus = function () {
  39887. //this._keys = [];
  39888. pointA = pointB = null;
  39889. previousPinchSquaredDistance = 0;
  39890. previousMultiTouchPanPosition.isPaning = false;
  39891. previousMultiTouchPanPosition.isPinching = false;
  39892. twoFingerActivityCount = 0;
  39893. cacheSoloPointer = null;
  39894. initialDistance = 0;
  39895. };
  39896. this._onMouseMove = function (evt) {
  39897. if (!engine.isPointerLock) {
  39898. return;
  39899. }
  39900. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39901. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39902. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39903. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39904. if (!noPreventDefault) {
  39905. evt.preventDefault();
  39906. }
  39907. };
  39908. this._onGestureStart = function (e) {
  39909. if (window.MSGesture === undefined) {
  39910. return;
  39911. }
  39912. if (!_this._MSGestureHandler) {
  39913. _this._MSGestureHandler = new MSGesture();
  39914. _this._MSGestureHandler.target = element;
  39915. }
  39916. _this._MSGestureHandler.addPointer(e.pointerId);
  39917. };
  39918. this._onGesture = function (e) {
  39919. _this.camera.radius *= e.scale;
  39920. if (e.preventDefault) {
  39921. if (!noPreventDefault) {
  39922. e.stopPropagation();
  39923. e.preventDefault();
  39924. }
  39925. }
  39926. };
  39927. element.addEventListener("mousemove", this._onMouseMove, false);
  39928. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39929. element.addEventListener("MSGestureChange", this._onGesture, false);
  39930. BABYLON.Tools.RegisterTopRootEvents([
  39931. { name: "blur", handler: this._onLostFocus }
  39932. ]);
  39933. };
  39934. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39935. if (this._onLostFocus) {
  39936. BABYLON.Tools.UnregisterTopRootEvents([
  39937. { name: "blur", handler: this._onLostFocus }
  39938. ]);
  39939. }
  39940. if (element && this._observer) {
  39941. this.camera.getScene().onPointerObservable.remove(this._observer);
  39942. this._observer = null;
  39943. if (this._onContextMenu) {
  39944. element.removeEventListener("contextmenu", this._onContextMenu);
  39945. }
  39946. if (this._onMouseMove) {
  39947. element.removeEventListener("mousemove", this._onMouseMove);
  39948. }
  39949. if (this._onGestureStart) {
  39950. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39951. }
  39952. if (this._onGesture) {
  39953. element.removeEventListener("MSGestureChange", this._onGesture);
  39954. }
  39955. this._isPanClick = false;
  39956. this.pinchInwards = true;
  39957. this._onMouseMove = null;
  39958. this._onGestureStart = null;
  39959. this._onGesture = null;
  39960. this._MSGestureHandler = null;
  39961. this._onLostFocus = null;
  39962. this._onContextMenu = null;
  39963. }
  39964. };
  39965. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39966. return "ArcRotateCameraPointersInput";
  39967. };
  39968. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39969. return "pointers";
  39970. };
  39971. __decorate([
  39972. BABYLON.serialize()
  39973. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39974. __decorate([
  39975. BABYLON.serialize()
  39976. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39977. __decorate([
  39978. BABYLON.serialize()
  39979. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39980. __decorate([
  39981. BABYLON.serialize()
  39982. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39983. __decorate([
  39984. BABYLON.serialize()
  39985. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39986. __decorate([
  39987. BABYLON.serialize()
  39988. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39989. __decorate([
  39990. BABYLON.serialize()
  39991. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39992. __decorate([
  39993. BABYLON.serialize()
  39994. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39995. return ArcRotateCameraPointersInput;
  39996. }());
  39997. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39998. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39999. })(BABYLON || (BABYLON = {}));
  40000. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40001. var BABYLON;
  40002. (function (BABYLON) {
  40003. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40004. __extends(ArcRotateCameraInputsManager, _super);
  40005. function ArcRotateCameraInputsManager(camera) {
  40006. return _super.call(this, camera) || this;
  40007. }
  40008. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40009. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40010. return this;
  40011. };
  40012. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40013. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40014. return this;
  40015. };
  40016. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40017. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40018. return this;
  40019. };
  40020. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40021. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40022. return this;
  40023. };
  40024. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40025. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40026. return this;
  40027. };
  40028. return ArcRotateCameraInputsManager;
  40029. }(BABYLON.CameraInputsManager));
  40030. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40031. })(BABYLON || (BABYLON = {}));
  40032. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40033. var BABYLON;
  40034. (function (BABYLON) {
  40035. var ArcRotateCamera = /** @class */ (function (_super) {
  40036. __extends(ArcRotateCamera, _super);
  40037. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40038. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40039. _this.inertialAlphaOffset = 0;
  40040. _this.inertialBetaOffset = 0;
  40041. _this.inertialRadiusOffset = 0;
  40042. _this.lowerAlphaLimit = null;
  40043. _this.upperAlphaLimit = null;
  40044. _this.lowerBetaLimit = 0.01;
  40045. _this.upperBetaLimit = Math.PI;
  40046. _this.lowerRadiusLimit = null;
  40047. _this.upperRadiusLimit = null;
  40048. _this.inertialPanningX = 0;
  40049. _this.inertialPanningY = 0;
  40050. _this.pinchToPanMaxDistance = 20;
  40051. _this.panningDistanceLimit = null;
  40052. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40053. _this.panningInertia = 0.9;
  40054. //-- end properties for backward compatibility for inputs
  40055. _this.zoomOnFactor = 1;
  40056. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40057. _this.allowUpsideDown = true;
  40058. _this._viewMatrix = new BABYLON.Matrix();
  40059. // Panning
  40060. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40061. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40062. _this.checkCollisions = false;
  40063. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40064. _this._previousPosition = BABYLON.Vector3.Zero();
  40065. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40066. _this._newPosition = BABYLON.Vector3.Zero();
  40067. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40068. if (collidedMesh === void 0) { collidedMesh = null; }
  40069. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40070. newPosition.multiplyInPlace(_this._collider._radius);
  40071. }
  40072. if (!collidedMesh) {
  40073. _this._previousPosition.copyFrom(_this.position);
  40074. }
  40075. else {
  40076. _this.setPosition(newPosition);
  40077. if (_this.onCollide) {
  40078. _this.onCollide(collidedMesh);
  40079. }
  40080. }
  40081. // Recompute because of constraints
  40082. var cosa = Math.cos(_this.alpha);
  40083. var sina = Math.sin(_this.alpha);
  40084. var cosb = Math.cos(_this.beta);
  40085. var sinb = Math.sin(_this.beta);
  40086. if (sinb === 0) {
  40087. sinb = 0.0001;
  40088. }
  40089. var target = _this._getTargetPosition();
  40090. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40091. _this.position.copyFrom(_this._newPosition);
  40092. var up = _this.upVector;
  40093. if (_this.allowUpsideDown && _this.beta < 0) {
  40094. up = up.clone();
  40095. up = up.negate();
  40096. }
  40097. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40098. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40099. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40100. _this._collisionTriggered = false;
  40101. };
  40102. _this._target = BABYLON.Vector3.Zero();
  40103. if (target) {
  40104. _this.setTarget(target);
  40105. }
  40106. _this.alpha = alpha;
  40107. _this.beta = beta;
  40108. _this.radius = radius;
  40109. _this.getViewMatrix();
  40110. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40111. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40112. return _this;
  40113. }
  40114. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40115. get: function () {
  40116. return this._target;
  40117. },
  40118. set: function (value) {
  40119. this.setTarget(value);
  40120. },
  40121. enumerable: true,
  40122. configurable: true
  40123. });
  40124. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40125. //-- begin properties for backward compatibility for inputs
  40126. get: function () {
  40127. var pointers = this.inputs.attached["pointers"];
  40128. if (pointers)
  40129. return pointers.angularSensibilityX;
  40130. return 0;
  40131. },
  40132. set: function (value) {
  40133. var pointers = this.inputs.attached["pointers"];
  40134. if (pointers) {
  40135. pointers.angularSensibilityX = value;
  40136. }
  40137. },
  40138. enumerable: true,
  40139. configurable: true
  40140. });
  40141. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40142. get: function () {
  40143. var pointers = this.inputs.attached["pointers"];
  40144. if (pointers)
  40145. return pointers.angularSensibilityY;
  40146. return 0;
  40147. },
  40148. set: function (value) {
  40149. var pointers = this.inputs.attached["pointers"];
  40150. if (pointers) {
  40151. pointers.angularSensibilityY = value;
  40152. }
  40153. },
  40154. enumerable: true,
  40155. configurable: true
  40156. });
  40157. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40158. get: function () {
  40159. var pointers = this.inputs.attached["pointers"];
  40160. if (pointers)
  40161. return pointers.pinchPrecision;
  40162. return 0;
  40163. },
  40164. set: function (value) {
  40165. var pointers = this.inputs.attached["pointers"];
  40166. if (pointers) {
  40167. pointers.pinchPrecision = value;
  40168. }
  40169. },
  40170. enumerable: true,
  40171. configurable: true
  40172. });
  40173. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40174. get: function () {
  40175. var pointers = this.inputs.attached["pointers"];
  40176. if (pointers)
  40177. return pointers.pinchDeltaPercentage;
  40178. return 0;
  40179. },
  40180. set: function (value) {
  40181. var pointers = this.inputs.attached["pointers"];
  40182. if (pointers) {
  40183. pointers.pinchDeltaPercentage = value;
  40184. }
  40185. },
  40186. enumerable: true,
  40187. configurable: true
  40188. });
  40189. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40190. get: function () {
  40191. var pointers = this.inputs.attached["pointers"];
  40192. if (pointers)
  40193. return pointers.panningSensibility;
  40194. return 0;
  40195. },
  40196. set: function (value) {
  40197. var pointers = this.inputs.attached["pointers"];
  40198. if (pointers) {
  40199. pointers.panningSensibility = value;
  40200. }
  40201. },
  40202. enumerable: true,
  40203. configurable: true
  40204. });
  40205. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40206. get: function () {
  40207. var keyboard = this.inputs.attached["keyboard"];
  40208. if (keyboard)
  40209. return keyboard.keysUp;
  40210. return [];
  40211. },
  40212. set: function (value) {
  40213. var keyboard = this.inputs.attached["keyboard"];
  40214. if (keyboard)
  40215. keyboard.keysUp = value;
  40216. },
  40217. enumerable: true,
  40218. configurable: true
  40219. });
  40220. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40221. get: function () {
  40222. var keyboard = this.inputs.attached["keyboard"];
  40223. if (keyboard)
  40224. return keyboard.keysDown;
  40225. return [];
  40226. },
  40227. set: function (value) {
  40228. var keyboard = this.inputs.attached["keyboard"];
  40229. if (keyboard)
  40230. keyboard.keysDown = value;
  40231. },
  40232. enumerable: true,
  40233. configurable: true
  40234. });
  40235. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40236. get: function () {
  40237. var keyboard = this.inputs.attached["keyboard"];
  40238. if (keyboard)
  40239. return keyboard.keysLeft;
  40240. return [];
  40241. },
  40242. set: function (value) {
  40243. var keyboard = this.inputs.attached["keyboard"];
  40244. if (keyboard)
  40245. keyboard.keysLeft = value;
  40246. },
  40247. enumerable: true,
  40248. configurable: true
  40249. });
  40250. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40251. get: function () {
  40252. var keyboard = this.inputs.attached["keyboard"];
  40253. if (keyboard)
  40254. return keyboard.keysRight;
  40255. return [];
  40256. },
  40257. set: function (value) {
  40258. var keyboard = this.inputs.attached["keyboard"];
  40259. if (keyboard)
  40260. keyboard.keysRight = value;
  40261. },
  40262. enumerable: true,
  40263. configurable: true
  40264. });
  40265. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40266. get: function () {
  40267. var mousewheel = this.inputs.attached["mousewheel"];
  40268. if (mousewheel)
  40269. return mousewheel.wheelPrecision;
  40270. return 0;
  40271. },
  40272. set: function (value) {
  40273. var mousewheel = this.inputs.attached["mousewheel"];
  40274. if (mousewheel)
  40275. mousewheel.wheelPrecision = value;
  40276. },
  40277. enumerable: true,
  40278. configurable: true
  40279. });
  40280. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40281. get: function () {
  40282. var mousewheel = this.inputs.attached["mousewheel"];
  40283. if (mousewheel)
  40284. return mousewheel.wheelDeltaPercentage;
  40285. return 0;
  40286. },
  40287. set: function (value) {
  40288. var mousewheel = this.inputs.attached["mousewheel"];
  40289. if (mousewheel)
  40290. mousewheel.wheelDeltaPercentage = value;
  40291. },
  40292. enumerable: true,
  40293. configurable: true
  40294. });
  40295. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40296. get: function () {
  40297. return this._bouncingBehavior;
  40298. },
  40299. enumerable: true,
  40300. configurable: true
  40301. });
  40302. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40303. get: function () {
  40304. return this._bouncingBehavior != null;
  40305. },
  40306. set: function (value) {
  40307. if (value === this.useBouncingBehavior) {
  40308. return;
  40309. }
  40310. if (value) {
  40311. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40312. this.addBehavior(this._bouncingBehavior);
  40313. }
  40314. else if (this._bouncingBehavior) {
  40315. this.removeBehavior(this._bouncingBehavior);
  40316. this._bouncingBehavior = null;
  40317. }
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40323. get: function () {
  40324. return this._framingBehavior;
  40325. },
  40326. enumerable: true,
  40327. configurable: true
  40328. });
  40329. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40330. get: function () {
  40331. return this._framingBehavior != null;
  40332. },
  40333. set: function (value) {
  40334. if (value === this.useFramingBehavior) {
  40335. return;
  40336. }
  40337. if (value) {
  40338. this._framingBehavior = new BABYLON.FramingBehavior();
  40339. this.addBehavior(this._framingBehavior);
  40340. }
  40341. else if (this._framingBehavior) {
  40342. this.removeBehavior(this._framingBehavior);
  40343. this._framingBehavior = null;
  40344. }
  40345. },
  40346. enumerable: true,
  40347. configurable: true
  40348. });
  40349. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40350. get: function () {
  40351. return this._autoRotationBehavior;
  40352. },
  40353. enumerable: true,
  40354. configurable: true
  40355. });
  40356. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40357. get: function () {
  40358. return this._autoRotationBehavior != null;
  40359. },
  40360. set: function (value) {
  40361. if (value === this.useAutoRotationBehavior) {
  40362. return;
  40363. }
  40364. if (value) {
  40365. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40366. this.addBehavior(this._autoRotationBehavior);
  40367. }
  40368. else if (this._autoRotationBehavior) {
  40369. this.removeBehavior(this._autoRotationBehavior);
  40370. this._autoRotationBehavior = null;
  40371. }
  40372. },
  40373. enumerable: true,
  40374. configurable: true
  40375. });
  40376. // Cache
  40377. ArcRotateCamera.prototype._initCache = function () {
  40378. _super.prototype._initCache.call(this);
  40379. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40380. this._cache.alpha = undefined;
  40381. this._cache.beta = undefined;
  40382. this._cache.radius = undefined;
  40383. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40384. };
  40385. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40386. if (!ignoreParentClass) {
  40387. _super.prototype._updateCache.call(this);
  40388. }
  40389. this._cache._target.copyFrom(this._getTargetPosition());
  40390. this._cache.alpha = this.alpha;
  40391. this._cache.beta = this.beta;
  40392. this._cache.radius = this.radius;
  40393. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40394. };
  40395. ArcRotateCamera.prototype._getTargetPosition = function () {
  40396. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40397. var pos = this._targetHost.getAbsolutePosition();
  40398. if (this._targetBoundingCenter) {
  40399. pos.addToRef(this._targetBoundingCenter, this._target);
  40400. }
  40401. else {
  40402. this._target.copyFrom(pos);
  40403. }
  40404. }
  40405. var lockedTargetPosition = this._getLockedTargetPosition();
  40406. if (lockedTargetPosition) {
  40407. return lockedTargetPosition;
  40408. }
  40409. return this._target;
  40410. };
  40411. ArcRotateCamera.prototype.storeState = function () {
  40412. this._storedAlpha = this.alpha;
  40413. this._storedBeta = this.beta;
  40414. this._storedRadius = this.radius;
  40415. this._storedTarget = this._getTargetPosition().clone();
  40416. return _super.prototype.storeState.call(this);
  40417. };
  40418. /**
  40419. * Restored camera state. You must call storeState() first
  40420. */
  40421. ArcRotateCamera.prototype._restoreStateValues = function () {
  40422. if (!_super.prototype._restoreStateValues.call(this)) {
  40423. return false;
  40424. }
  40425. this.alpha = this._storedAlpha;
  40426. this.beta = this._storedBeta;
  40427. this.radius = this._storedRadius;
  40428. this.setTarget(this._storedTarget.clone());
  40429. this.inertialAlphaOffset = 0;
  40430. this.inertialBetaOffset = 0;
  40431. this.inertialRadiusOffset = 0;
  40432. this.inertialPanningX = 0;
  40433. this.inertialPanningY = 0;
  40434. return true;
  40435. };
  40436. // Synchronized
  40437. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40438. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40439. return false;
  40440. return this._cache._target.equals(this._getTargetPosition())
  40441. && this._cache.alpha === this.alpha
  40442. && this._cache.beta === this.beta
  40443. && this._cache.radius === this.radius
  40444. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40445. };
  40446. // Methods
  40447. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40448. var _this = this;
  40449. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40450. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40451. this._useCtrlForPanning = useCtrlForPanning;
  40452. this._panningMouseButton = panningMouseButton;
  40453. this.inputs.attachElement(element, noPreventDefault);
  40454. this._reset = function () {
  40455. _this.inertialAlphaOffset = 0;
  40456. _this.inertialBetaOffset = 0;
  40457. _this.inertialRadiusOffset = 0;
  40458. _this.inertialPanningX = 0;
  40459. _this.inertialPanningY = 0;
  40460. };
  40461. };
  40462. ArcRotateCamera.prototype.detachControl = function (element) {
  40463. this.inputs.detachElement(element);
  40464. if (this._reset) {
  40465. this._reset();
  40466. }
  40467. };
  40468. ArcRotateCamera.prototype._checkInputs = function () {
  40469. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40470. if (this._collisionTriggered) {
  40471. return;
  40472. }
  40473. this.inputs.checkInputs();
  40474. // Inertia
  40475. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40476. if (this.getScene().useRightHandedSystem) {
  40477. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40478. }
  40479. else {
  40480. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40481. }
  40482. this.beta += this.inertialBetaOffset;
  40483. this.radius -= this.inertialRadiusOffset;
  40484. this.inertialAlphaOffset *= this.inertia;
  40485. this.inertialBetaOffset *= this.inertia;
  40486. this.inertialRadiusOffset *= this.inertia;
  40487. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40488. this.inertialAlphaOffset = 0;
  40489. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40490. this.inertialBetaOffset = 0;
  40491. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40492. this.inertialRadiusOffset = 0;
  40493. }
  40494. // Panning inertia
  40495. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40496. if (!this._localDirection) {
  40497. this._localDirection = BABYLON.Vector3.Zero();
  40498. this._transformedDirection = BABYLON.Vector3.Zero();
  40499. }
  40500. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40501. this._localDirection.multiplyInPlace(this.panningAxis);
  40502. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40503. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40504. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40505. if (!this.panningAxis.y) {
  40506. this._transformedDirection.y = 0;
  40507. }
  40508. if (!this._targetHost) {
  40509. if (this.panningDistanceLimit) {
  40510. this._transformedDirection.addInPlace(this._target);
  40511. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40512. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40513. this._target.copyFrom(this._transformedDirection);
  40514. }
  40515. }
  40516. else {
  40517. this._target.addInPlace(this._transformedDirection);
  40518. }
  40519. }
  40520. this.inertialPanningX *= this.panningInertia;
  40521. this.inertialPanningY *= this.panningInertia;
  40522. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40523. this.inertialPanningX = 0;
  40524. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40525. this.inertialPanningY = 0;
  40526. }
  40527. // Limits
  40528. this._checkLimits();
  40529. _super.prototype._checkInputs.call(this);
  40530. };
  40531. ArcRotateCamera.prototype._checkLimits = function () {
  40532. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40533. if (this.allowUpsideDown && this.beta > Math.PI) {
  40534. this.beta = this.beta - (2 * Math.PI);
  40535. }
  40536. }
  40537. else {
  40538. if (this.beta < this.lowerBetaLimit) {
  40539. this.beta = this.lowerBetaLimit;
  40540. }
  40541. }
  40542. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40543. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40544. this.beta = this.beta + (2 * Math.PI);
  40545. }
  40546. }
  40547. else {
  40548. if (this.beta > this.upperBetaLimit) {
  40549. this.beta = this.upperBetaLimit;
  40550. }
  40551. }
  40552. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40553. this.alpha = this.lowerAlphaLimit;
  40554. }
  40555. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40556. this.alpha = this.upperAlphaLimit;
  40557. }
  40558. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40559. this.radius = this.lowerRadiusLimit;
  40560. }
  40561. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40562. this.radius = this.upperRadiusLimit;
  40563. }
  40564. };
  40565. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40566. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40567. this.radius = radiusv3.length();
  40568. if (this.radius === 0) {
  40569. this.radius = 0.0001; // Just to avoid division by zero
  40570. }
  40571. // Alpha
  40572. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40573. if (radiusv3.z < 0) {
  40574. this.alpha = 2 * Math.PI - this.alpha;
  40575. }
  40576. // Beta
  40577. this.beta = Math.acos(radiusv3.y / this.radius);
  40578. this._checkLimits();
  40579. };
  40580. ArcRotateCamera.prototype.setPosition = function (position) {
  40581. if (this.position.equals(position)) {
  40582. return;
  40583. }
  40584. this.position.copyFrom(position);
  40585. this.rebuildAnglesAndRadius();
  40586. };
  40587. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40588. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40589. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40590. if (target.getBoundingInfo) {
  40591. if (toBoundingCenter) {
  40592. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40593. }
  40594. else {
  40595. this._targetBoundingCenter = null;
  40596. }
  40597. this._targetHost = target;
  40598. this._target = this._getTargetPosition();
  40599. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40600. }
  40601. else {
  40602. var newTarget = target;
  40603. var currentTarget = this._getTargetPosition();
  40604. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40605. return;
  40606. }
  40607. this._targetHost = null;
  40608. this._target = newTarget;
  40609. this._targetBoundingCenter = null;
  40610. this.onMeshTargetChangedObservable.notifyObservers(null);
  40611. }
  40612. this.rebuildAnglesAndRadius();
  40613. };
  40614. ArcRotateCamera.prototype._getViewMatrix = function () {
  40615. // Compute
  40616. var cosa = Math.cos(this.alpha);
  40617. var sina = Math.sin(this.alpha);
  40618. var cosb = Math.cos(this.beta);
  40619. var sinb = Math.sin(this.beta);
  40620. if (sinb === 0) {
  40621. sinb = 0.0001;
  40622. }
  40623. var target = this._getTargetPosition();
  40624. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40625. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40626. if (!this._collider) {
  40627. this._collider = new BABYLON.Collider();
  40628. }
  40629. this._collider._radius = this.collisionRadius;
  40630. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40631. this._collisionTriggered = true;
  40632. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40633. }
  40634. else {
  40635. this.position.copyFrom(this._newPosition);
  40636. var up = this.upVector;
  40637. if (this.allowUpsideDown && sinb < 0) {
  40638. up = up.clone();
  40639. up = up.negate();
  40640. }
  40641. if (this.getScene().useRightHandedSystem) {
  40642. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40643. }
  40644. else {
  40645. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40646. }
  40647. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40648. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40649. }
  40650. this._currentTarget = target;
  40651. return this._viewMatrix;
  40652. };
  40653. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40654. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40655. meshes = meshes || this.getScene().meshes;
  40656. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40657. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40658. this.radius = distance * this.zoomOnFactor;
  40659. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40660. };
  40661. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40662. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40663. var meshesOrMinMaxVector;
  40664. var distance;
  40665. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40666. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40667. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40668. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40669. }
  40670. else {
  40671. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40672. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40673. distance = minMaxVectorAndDistance.distance;
  40674. }
  40675. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40676. if (!doNotUpdateMaxZ) {
  40677. this.maxZ = distance * 2;
  40678. }
  40679. };
  40680. /**
  40681. * @override
  40682. * Override Camera.createRigCamera
  40683. */
  40684. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40685. var alphaShift = 0;
  40686. switch (this.cameraRigMode) {
  40687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40690. case BABYLON.Camera.RIG_MODE_VR:
  40691. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40692. break;
  40693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40694. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40695. break;
  40696. }
  40697. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40698. rigCam._cameraRigParams = {};
  40699. return rigCam;
  40700. };
  40701. /**
  40702. * @override
  40703. * Override Camera._updateRigCameras
  40704. */
  40705. ArcRotateCamera.prototype._updateRigCameras = function () {
  40706. var camLeft = this._rigCameras[0];
  40707. var camRight = this._rigCameras[1];
  40708. camLeft.beta = camRight.beta = this.beta;
  40709. camLeft.radius = camRight.radius = this.radius;
  40710. switch (this.cameraRigMode) {
  40711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40714. case BABYLON.Camera.RIG_MODE_VR:
  40715. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40716. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40717. break;
  40718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40719. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40720. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40721. break;
  40722. }
  40723. _super.prototype._updateRigCameras.call(this);
  40724. };
  40725. ArcRotateCamera.prototype.dispose = function () {
  40726. this.inputs.clear();
  40727. _super.prototype.dispose.call(this);
  40728. };
  40729. ArcRotateCamera.prototype.getClassName = function () {
  40730. return "ArcRotateCamera";
  40731. };
  40732. __decorate([
  40733. BABYLON.serialize()
  40734. ], ArcRotateCamera.prototype, "alpha", void 0);
  40735. __decorate([
  40736. BABYLON.serialize()
  40737. ], ArcRotateCamera.prototype, "beta", void 0);
  40738. __decorate([
  40739. BABYLON.serialize()
  40740. ], ArcRotateCamera.prototype, "radius", void 0);
  40741. __decorate([
  40742. BABYLON.serializeAsVector3("target")
  40743. ], ArcRotateCamera.prototype, "_target", void 0);
  40744. __decorate([
  40745. BABYLON.serialize()
  40746. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40747. __decorate([
  40748. BABYLON.serialize()
  40749. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40750. __decorate([
  40751. BABYLON.serialize()
  40752. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40753. __decorate([
  40754. BABYLON.serialize()
  40755. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40756. __decorate([
  40757. BABYLON.serialize()
  40758. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40759. __decorate([
  40760. BABYLON.serialize()
  40761. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40762. __decorate([
  40763. BABYLON.serialize()
  40764. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40765. __decorate([
  40766. BABYLON.serialize()
  40767. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40768. __decorate([
  40769. BABYLON.serialize()
  40770. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40771. __decorate([
  40772. BABYLON.serialize()
  40773. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40774. __decorate([
  40775. BABYLON.serialize()
  40776. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40777. __decorate([
  40778. BABYLON.serialize()
  40779. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40780. __decorate([
  40781. BABYLON.serialize()
  40782. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40783. __decorate([
  40784. BABYLON.serializeAsVector3()
  40785. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40786. __decorate([
  40787. BABYLON.serialize()
  40788. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40789. __decorate([
  40790. BABYLON.serialize()
  40791. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40792. __decorate([
  40793. BABYLON.serialize()
  40794. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40795. return ArcRotateCamera;
  40796. }(BABYLON.TargetCamera));
  40797. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40798. })(BABYLON || (BABYLON = {}));
  40799. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40800. var BABYLON;
  40801. (function (BABYLON) {
  40802. var HemisphericLight = /** @class */ (function (_super) {
  40803. __extends(HemisphericLight, _super);
  40804. /**
  40805. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40806. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40807. * The HemisphericLight can't cast shadows.
  40808. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40809. */
  40810. function HemisphericLight(name, direction, scene) {
  40811. var _this = _super.call(this, name, scene) || this;
  40812. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40813. _this.direction = direction || BABYLON.Vector3.Up();
  40814. return _this;
  40815. }
  40816. HemisphericLight.prototype._buildUniformLayout = function () {
  40817. this._uniformBuffer.addUniform("vLightData", 4);
  40818. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40819. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40820. this._uniformBuffer.addUniform("vLightGround", 3);
  40821. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40822. this._uniformBuffer.addUniform("depthValues", 2);
  40823. this._uniformBuffer.create();
  40824. };
  40825. /**
  40826. * Returns the string "HemisphericLight".
  40827. */
  40828. HemisphericLight.prototype.getClassName = function () {
  40829. return "HemisphericLight";
  40830. };
  40831. /**
  40832. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40833. * Returns the updated direction.
  40834. */
  40835. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40836. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40837. return this.direction;
  40838. };
  40839. HemisphericLight.prototype.getShadowGenerator = function () {
  40840. return null;
  40841. };
  40842. /**
  40843. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40844. * Returns the HemisphericLight.
  40845. */
  40846. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40847. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40848. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40849. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40850. return this;
  40851. };
  40852. HemisphericLight.prototype._getWorldMatrix = function () {
  40853. if (!this._worldMatrix) {
  40854. this._worldMatrix = BABYLON.Matrix.Identity();
  40855. }
  40856. return this._worldMatrix;
  40857. };
  40858. /**
  40859. * Returns the integer 3.
  40860. */
  40861. HemisphericLight.prototype.getTypeID = function () {
  40862. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40863. };
  40864. __decorate([
  40865. BABYLON.serializeAsColor3()
  40866. ], HemisphericLight.prototype, "groundColor", void 0);
  40867. __decorate([
  40868. BABYLON.serializeAsVector3()
  40869. ], HemisphericLight.prototype, "direction", void 0);
  40870. return HemisphericLight;
  40871. }(BABYLON.Light));
  40872. BABYLON.HemisphericLight = HemisphericLight;
  40873. })(BABYLON || (BABYLON = {}));
  40874. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40875. var BABYLON;
  40876. (function (BABYLON) {
  40877. var ShadowLight = /** @class */ (function (_super) {
  40878. __extends(ShadowLight, _super);
  40879. function ShadowLight() {
  40880. var _this = _super !== null && _super.apply(this, arguments) || this;
  40881. _this._needProjectionMatrixCompute = true;
  40882. return _this;
  40883. }
  40884. Object.defineProperty(ShadowLight.prototype, "direction", {
  40885. get: function () {
  40886. return this._direction;
  40887. },
  40888. set: function (value) {
  40889. this._direction = value;
  40890. },
  40891. enumerable: true,
  40892. configurable: true
  40893. });
  40894. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40895. get: function () {
  40896. return this._shadowMinZ;
  40897. },
  40898. set: function (value) {
  40899. this._shadowMinZ = value;
  40900. this.forceProjectionMatrixCompute();
  40901. },
  40902. enumerable: true,
  40903. configurable: true
  40904. });
  40905. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40906. get: function () {
  40907. return this._shadowMaxZ;
  40908. },
  40909. set: function (value) {
  40910. this._shadowMaxZ = value;
  40911. this.forceProjectionMatrixCompute();
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. /**
  40917. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40918. */
  40919. ShadowLight.prototype.computeTransformedInformation = function () {
  40920. if (this.parent && this.parent.getWorldMatrix) {
  40921. if (!this.transformedPosition) {
  40922. this.transformedPosition = BABYLON.Vector3.Zero();
  40923. }
  40924. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40925. // In case the direction is present.
  40926. if (this.direction) {
  40927. if (!this.transformedDirection) {
  40928. this.transformedDirection = BABYLON.Vector3.Zero();
  40929. }
  40930. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40931. }
  40932. return true;
  40933. }
  40934. return false;
  40935. };
  40936. /**
  40937. * Return the depth scale used for the shadow map.
  40938. */
  40939. ShadowLight.prototype.getDepthScale = function () {
  40940. return 50.0;
  40941. };
  40942. /**
  40943. * Returns the light direction (Vector3) for any passed face index.
  40944. */
  40945. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40946. return this.transformedDirection ? this.transformedDirection : this.direction;
  40947. };
  40948. /**
  40949. * Returns the DirectionalLight absolute position in the World.
  40950. */
  40951. ShadowLight.prototype.getAbsolutePosition = function () {
  40952. return this.transformedPosition ? this.transformedPosition : this.position;
  40953. };
  40954. /**
  40955. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40956. * Returns the updated DirectionalLight direction (Vector3).
  40957. */
  40958. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40959. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40960. return this.direction;
  40961. };
  40962. /**
  40963. * Returns the light rotation (Vector3).
  40964. */
  40965. ShadowLight.prototype.getRotation = function () {
  40966. this.direction.normalize();
  40967. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40968. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40969. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40970. };
  40971. /**
  40972. * Boolean : false by default.
  40973. */
  40974. ShadowLight.prototype.needCube = function () {
  40975. return false;
  40976. };
  40977. /**
  40978. * Specifies wether or not the projection matrix should be recomputed this frame.
  40979. */
  40980. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40981. return this._needProjectionMatrixCompute;
  40982. };
  40983. /**
  40984. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40985. */
  40986. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40987. this._needProjectionMatrixCompute = true;
  40988. };
  40989. /**
  40990. * Get the world matrix of the sahdow lights.
  40991. */
  40992. ShadowLight.prototype._getWorldMatrix = function () {
  40993. if (!this._worldMatrix) {
  40994. this._worldMatrix = BABYLON.Matrix.Identity();
  40995. }
  40996. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40997. return this._worldMatrix;
  40998. };
  40999. /**
  41000. * Gets the minZ used for shadow according to both the scene and the light.
  41001. * @param activeCamera
  41002. */
  41003. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41004. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41005. };
  41006. /**
  41007. * Gets the maxZ used for shadow according to both the scene and the light.
  41008. * @param activeCamera
  41009. */
  41010. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41011. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41012. };
  41013. /**
  41014. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41015. * Returns the light.
  41016. */
  41017. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41018. if (this.customProjectionMatrixBuilder) {
  41019. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41020. }
  41021. else {
  41022. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41023. }
  41024. return this;
  41025. };
  41026. __decorate([
  41027. BABYLON.serializeAsVector3()
  41028. ], ShadowLight.prototype, "position", void 0);
  41029. __decorate([
  41030. BABYLON.serializeAsVector3()
  41031. ], ShadowLight.prototype, "direction", null);
  41032. __decorate([
  41033. BABYLON.serialize()
  41034. ], ShadowLight.prototype, "shadowMinZ", null);
  41035. __decorate([
  41036. BABYLON.serialize()
  41037. ], ShadowLight.prototype, "shadowMaxZ", null);
  41038. return ShadowLight;
  41039. }(BABYLON.Light));
  41040. BABYLON.ShadowLight = ShadowLight;
  41041. })(BABYLON || (BABYLON = {}));
  41042. //# sourceMappingURL=babylon.shadowLight.js.map
  41043. var BABYLON;
  41044. (function (BABYLON) {
  41045. var PointLight = /** @class */ (function (_super) {
  41046. __extends(PointLight, _super);
  41047. /**
  41048. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41049. * A PointLight emits the light in every direction.
  41050. * It can cast shadows.
  41051. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41052. * ```javascript
  41053. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41054. * ```
  41055. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41056. */
  41057. function PointLight(name, position, scene) {
  41058. var _this = _super.call(this, name, scene) || this;
  41059. _this._shadowAngle = Math.PI / 2;
  41060. _this.position = position;
  41061. return _this;
  41062. }
  41063. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41064. /**
  41065. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41066. * This specifies what angle the shadow will use to be created.
  41067. *
  41068. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41069. */
  41070. get: function () {
  41071. return this._shadowAngle;
  41072. },
  41073. /**
  41074. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41075. * This specifies what angle the shadow will use to be created.
  41076. *
  41077. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41078. */
  41079. set: function (value) {
  41080. this._shadowAngle = value;
  41081. this.forceProjectionMatrixCompute();
  41082. },
  41083. enumerable: true,
  41084. configurable: true
  41085. });
  41086. Object.defineProperty(PointLight.prototype, "direction", {
  41087. get: function () {
  41088. return this._direction;
  41089. },
  41090. /**
  41091. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41092. */
  41093. set: function (value) {
  41094. var previousNeedCube = this.needCube();
  41095. this._direction = value;
  41096. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41097. this._shadowGenerator.recreateShadowMap();
  41098. }
  41099. },
  41100. enumerable: true,
  41101. configurable: true
  41102. });
  41103. /**
  41104. * Returns the string "PointLight"
  41105. */
  41106. PointLight.prototype.getClassName = function () {
  41107. return "PointLight";
  41108. };
  41109. /**
  41110. * Returns the integer 0.
  41111. */
  41112. PointLight.prototype.getTypeID = function () {
  41113. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41114. };
  41115. /**
  41116. * Specifies wether or not the shadowmap should be a cube texture.
  41117. */
  41118. PointLight.prototype.needCube = function () {
  41119. return !this.direction;
  41120. };
  41121. /**
  41122. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41123. */
  41124. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41125. if (this.direction) {
  41126. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41127. }
  41128. else {
  41129. switch (faceIndex) {
  41130. case 0:
  41131. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41132. case 1:
  41133. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41134. case 2:
  41135. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41136. case 3:
  41137. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41138. case 4:
  41139. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41140. case 5:
  41141. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41142. }
  41143. }
  41144. return BABYLON.Vector3.Zero();
  41145. };
  41146. /**
  41147. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41148. * - fov = PI / 2
  41149. * - aspect ratio : 1.0
  41150. * - z-near and far equal to the active camera minZ and maxZ.
  41151. * Returns the PointLight.
  41152. */
  41153. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41154. var activeCamera = this.getScene().activeCamera;
  41155. if (!activeCamera) {
  41156. return;
  41157. }
  41158. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41159. };
  41160. PointLight.prototype._buildUniformLayout = function () {
  41161. this._uniformBuffer.addUniform("vLightData", 4);
  41162. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41163. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41164. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41165. this._uniformBuffer.addUniform("depthValues", 2);
  41166. this._uniformBuffer.create();
  41167. };
  41168. /**
  41169. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41170. * Returns the PointLight.
  41171. */
  41172. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41173. if (this.computeTransformedInformation()) {
  41174. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41175. return this;
  41176. }
  41177. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41178. return this;
  41179. };
  41180. __decorate([
  41181. BABYLON.serialize()
  41182. ], PointLight.prototype, "shadowAngle", null);
  41183. return PointLight;
  41184. }(BABYLON.ShadowLight));
  41185. BABYLON.PointLight = PointLight;
  41186. })(BABYLON || (BABYLON = {}));
  41187. //# sourceMappingURL=babylon.pointLight.js.map
  41188. var BABYLON;
  41189. (function (BABYLON) {
  41190. var DirectionalLight = /** @class */ (function (_super) {
  41191. __extends(DirectionalLight, _super);
  41192. /**
  41193. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41194. * The directional light is emitted from everywhere in the given direction.
  41195. * It can cast shawdows.
  41196. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41197. */
  41198. function DirectionalLight(name, direction, scene) {
  41199. var _this = _super.call(this, name, scene) || this;
  41200. _this._shadowFrustumSize = 0;
  41201. _this._shadowOrthoScale = 0.5;
  41202. _this.autoUpdateExtends = true;
  41203. // Cache
  41204. _this._orthoLeft = Number.MAX_VALUE;
  41205. _this._orthoRight = Number.MIN_VALUE;
  41206. _this._orthoTop = Number.MIN_VALUE;
  41207. _this._orthoBottom = Number.MAX_VALUE;
  41208. _this.position = direction.scale(-1.0);
  41209. _this.direction = direction;
  41210. return _this;
  41211. }
  41212. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41213. /**
  41214. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41215. */
  41216. get: function () {
  41217. return this._shadowFrustumSize;
  41218. },
  41219. /**
  41220. * Specifies a fix frustum size for the shadow generation.
  41221. */
  41222. set: function (value) {
  41223. this._shadowFrustumSize = value;
  41224. this.forceProjectionMatrixCompute();
  41225. },
  41226. enumerable: true,
  41227. configurable: true
  41228. });
  41229. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41230. get: function () {
  41231. return this._shadowOrthoScale;
  41232. },
  41233. set: function (value) {
  41234. this._shadowOrthoScale = value;
  41235. this.forceProjectionMatrixCompute();
  41236. },
  41237. enumerable: true,
  41238. configurable: true
  41239. });
  41240. /**
  41241. * Returns the string "DirectionalLight".
  41242. */
  41243. DirectionalLight.prototype.getClassName = function () {
  41244. return "DirectionalLight";
  41245. };
  41246. /**
  41247. * Returns the integer 1.
  41248. */
  41249. DirectionalLight.prototype.getTypeID = function () {
  41250. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41251. };
  41252. /**
  41253. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41254. * Returns the DirectionalLight Shadow projection matrix.
  41255. */
  41256. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41257. if (this.shadowFrustumSize > 0) {
  41258. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41259. }
  41260. else {
  41261. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41262. }
  41263. };
  41264. /**
  41265. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41266. * Returns the DirectionalLight Shadow projection matrix.
  41267. */
  41268. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41269. var activeCamera = this.getScene().activeCamera;
  41270. if (!activeCamera) {
  41271. return;
  41272. }
  41273. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41274. };
  41275. /**
  41276. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41277. * Returns the DirectionalLight Shadow projection matrix.
  41278. */
  41279. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41280. var activeCamera = this.getScene().activeCamera;
  41281. if (!activeCamera) {
  41282. return;
  41283. }
  41284. // Check extends
  41285. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41286. var tempVector3 = BABYLON.Vector3.Zero();
  41287. this._orthoLeft = Number.MAX_VALUE;
  41288. this._orthoRight = Number.MIN_VALUE;
  41289. this._orthoTop = Number.MIN_VALUE;
  41290. this._orthoBottom = Number.MAX_VALUE;
  41291. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41292. var mesh = renderList[meshIndex];
  41293. if (!mesh) {
  41294. continue;
  41295. }
  41296. var boundingInfo = mesh.getBoundingInfo();
  41297. var boundingBox = boundingInfo.boundingBox;
  41298. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41299. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41300. if (tempVector3.x < this._orthoLeft)
  41301. this._orthoLeft = tempVector3.x;
  41302. if (tempVector3.y < this._orthoBottom)
  41303. this._orthoBottom = tempVector3.y;
  41304. if (tempVector3.x > this._orthoRight)
  41305. this._orthoRight = tempVector3.x;
  41306. if (tempVector3.y > this._orthoTop)
  41307. this._orthoTop = tempVector3.y;
  41308. }
  41309. }
  41310. }
  41311. var xOffset = this._orthoRight - this._orthoLeft;
  41312. var yOffset = this._orthoTop - this._orthoBottom;
  41313. 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);
  41314. };
  41315. DirectionalLight.prototype._buildUniformLayout = function () {
  41316. this._uniformBuffer.addUniform("vLightData", 4);
  41317. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41318. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41319. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41320. this._uniformBuffer.addUniform("depthValues", 2);
  41321. this._uniformBuffer.create();
  41322. };
  41323. /**
  41324. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41325. * Returns the DirectionalLight.
  41326. */
  41327. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41328. if (this.computeTransformedInformation()) {
  41329. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41330. return this;
  41331. }
  41332. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41333. return this;
  41334. };
  41335. /**
  41336. * Gets the minZ used for shadow according to both the scene and the light.
  41337. *
  41338. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41339. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41340. * @param activeCamera
  41341. */
  41342. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41343. return 1;
  41344. };
  41345. /**
  41346. * Gets the maxZ used for shadow according to both the scene and the light.
  41347. *
  41348. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41349. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41350. * @param activeCamera
  41351. */
  41352. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41353. return 1;
  41354. };
  41355. __decorate([
  41356. BABYLON.serialize()
  41357. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41358. __decorate([
  41359. BABYLON.serialize()
  41360. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41361. __decorate([
  41362. BABYLON.serialize()
  41363. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41364. return DirectionalLight;
  41365. }(BABYLON.ShadowLight));
  41366. BABYLON.DirectionalLight = DirectionalLight;
  41367. })(BABYLON || (BABYLON = {}));
  41368. //# sourceMappingURL=babylon.directionalLight.js.map
  41369. var BABYLON;
  41370. (function (BABYLON) {
  41371. var SpotLight = /** @class */ (function (_super) {
  41372. __extends(SpotLight, _super);
  41373. /**
  41374. * Creates a SpotLight object in the scene with the passed parameters :
  41375. * - `position` (Vector3) is the initial SpotLight position,
  41376. * - `direction` (Vector3) is the initial SpotLight direction,
  41377. * - `angle` (float, in radians) is the spot light cone angle,
  41378. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41379. * A spot light is a simply light oriented cone.
  41380. * It can cast shadows.
  41381. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41382. */
  41383. function SpotLight(name, position, direction, angle, exponent, scene) {
  41384. var _this = _super.call(this, name, scene) || this;
  41385. _this.position = position;
  41386. _this.direction = direction;
  41387. _this.angle = angle;
  41388. _this.exponent = exponent;
  41389. return _this;
  41390. }
  41391. Object.defineProperty(SpotLight.prototype, "angle", {
  41392. get: function () {
  41393. return this._angle;
  41394. },
  41395. set: function (value) {
  41396. this._angle = value;
  41397. this.forceProjectionMatrixCompute();
  41398. },
  41399. enumerable: true,
  41400. configurable: true
  41401. });
  41402. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41403. get: function () {
  41404. return this._shadowAngleScale;
  41405. },
  41406. /**
  41407. * Allows scaling the angle of the light for shadow generation only.
  41408. */
  41409. set: function (value) {
  41410. this._shadowAngleScale = value;
  41411. this.forceProjectionMatrixCompute();
  41412. },
  41413. enumerable: true,
  41414. configurable: true
  41415. });
  41416. /**
  41417. * Returns the string "SpotLight".
  41418. */
  41419. SpotLight.prototype.getClassName = function () {
  41420. return "SpotLight";
  41421. };
  41422. /**
  41423. * Returns the integer 2.
  41424. */
  41425. SpotLight.prototype.getTypeID = function () {
  41426. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41427. };
  41428. /**
  41429. * 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.
  41430. * Returns the SpotLight.
  41431. */
  41432. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41433. var activeCamera = this.getScene().activeCamera;
  41434. if (!activeCamera) {
  41435. return;
  41436. }
  41437. this._shadowAngleScale = this._shadowAngleScale || 1;
  41438. var angle = this._shadowAngleScale * this._angle;
  41439. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41440. };
  41441. SpotLight.prototype._buildUniformLayout = function () {
  41442. this._uniformBuffer.addUniform("vLightData", 4);
  41443. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41444. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41445. this._uniformBuffer.addUniform("vLightDirection", 3);
  41446. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41447. this._uniformBuffer.addUniform("depthValues", 2);
  41448. this._uniformBuffer.create();
  41449. };
  41450. /**
  41451. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41452. * Return the SpotLight.
  41453. */
  41454. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41455. var normalizeDirection;
  41456. if (this.computeTransformedInformation()) {
  41457. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41458. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41459. }
  41460. else {
  41461. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41462. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41463. }
  41464. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41465. return this;
  41466. };
  41467. __decorate([
  41468. BABYLON.serialize()
  41469. ], SpotLight.prototype, "angle", null);
  41470. __decorate([
  41471. BABYLON.serialize()
  41472. /**
  41473. * Allows scaling the angle of the light for shadow generation only.
  41474. */
  41475. ], SpotLight.prototype, "shadowAngleScale", null);
  41476. __decorate([
  41477. BABYLON.serialize()
  41478. ], SpotLight.prototype, "exponent", void 0);
  41479. return SpotLight;
  41480. }(BABYLON.ShadowLight));
  41481. BABYLON.SpotLight = SpotLight;
  41482. })(BABYLON || (BABYLON = {}));
  41483. //# sourceMappingURL=babylon.spotLight.js.map
  41484. var BABYLON;
  41485. (function (BABYLON) {
  41486. var AnimationRange = /** @class */ (function () {
  41487. function AnimationRange(name, from, to) {
  41488. this.name = name;
  41489. this.from = from;
  41490. this.to = to;
  41491. }
  41492. AnimationRange.prototype.clone = function () {
  41493. return new AnimationRange(this.name, this.from, this.to);
  41494. };
  41495. return AnimationRange;
  41496. }());
  41497. BABYLON.AnimationRange = AnimationRange;
  41498. /**
  41499. * Composed of a frame, and an action function
  41500. */
  41501. var AnimationEvent = /** @class */ (function () {
  41502. function AnimationEvent(frame, action, onlyOnce) {
  41503. this.frame = frame;
  41504. this.action = action;
  41505. this.onlyOnce = onlyOnce;
  41506. this.isDone = false;
  41507. }
  41508. return AnimationEvent;
  41509. }());
  41510. BABYLON.AnimationEvent = AnimationEvent;
  41511. var PathCursor = /** @class */ (function () {
  41512. function PathCursor(path) {
  41513. this.path = path;
  41514. this._onchange = new Array();
  41515. this.value = 0;
  41516. this.animations = new Array();
  41517. }
  41518. PathCursor.prototype.getPoint = function () {
  41519. var point = this.path.getPointAtLengthPosition(this.value);
  41520. return new BABYLON.Vector3(point.x, 0, point.y);
  41521. };
  41522. PathCursor.prototype.moveAhead = function (step) {
  41523. if (step === void 0) { step = 0.002; }
  41524. this.move(step);
  41525. return this;
  41526. };
  41527. PathCursor.prototype.moveBack = function (step) {
  41528. if (step === void 0) { step = 0.002; }
  41529. this.move(-step);
  41530. return this;
  41531. };
  41532. PathCursor.prototype.move = function (step) {
  41533. if (Math.abs(step) > 1) {
  41534. throw "step size should be less than 1.";
  41535. }
  41536. this.value += step;
  41537. this.ensureLimits();
  41538. this.raiseOnChange();
  41539. return this;
  41540. };
  41541. PathCursor.prototype.ensureLimits = function () {
  41542. while (this.value > 1) {
  41543. this.value -= 1;
  41544. }
  41545. while (this.value < 0) {
  41546. this.value += 1;
  41547. }
  41548. return this;
  41549. };
  41550. // used by animation engine
  41551. PathCursor.prototype.raiseOnChange = function () {
  41552. var _this = this;
  41553. this._onchange.forEach(function (f) { return f(_this); });
  41554. return this;
  41555. };
  41556. PathCursor.prototype.onchange = function (f) {
  41557. this._onchange.push(f);
  41558. return this;
  41559. };
  41560. return PathCursor;
  41561. }());
  41562. BABYLON.PathCursor = PathCursor;
  41563. var AnimationKeyInterpolation;
  41564. (function (AnimationKeyInterpolation) {
  41565. /**
  41566. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41567. */
  41568. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41569. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41570. var Animation = /** @class */ (function () {
  41571. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41572. this.name = name;
  41573. this.targetProperty = targetProperty;
  41574. this.framePerSecond = framePerSecond;
  41575. this.dataType = dataType;
  41576. this.loopMode = loopMode;
  41577. this.enableBlending = enableBlending;
  41578. this._runtimeAnimations = new Array();
  41579. // The set of event that will be linked to this animation
  41580. this._events = new Array();
  41581. this.blendingSpeed = 0.01;
  41582. this._ranges = {};
  41583. this.targetPropertyPath = targetProperty.split(".");
  41584. this.dataType = dataType;
  41585. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41586. }
  41587. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41588. var dataType = undefined;
  41589. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41590. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41591. }
  41592. else if (from instanceof BABYLON.Quaternion) {
  41593. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41594. }
  41595. else if (from instanceof BABYLON.Vector3) {
  41596. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41597. }
  41598. else if (from instanceof BABYLON.Vector2) {
  41599. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41600. }
  41601. else if (from instanceof BABYLON.Color3) {
  41602. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41603. }
  41604. else if (from instanceof BABYLON.Size) {
  41605. dataType = Animation.ANIMATIONTYPE_SIZE;
  41606. }
  41607. if (dataType == undefined) {
  41608. return null;
  41609. }
  41610. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41611. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41612. animation.setKeys(keys);
  41613. if (easingFunction !== undefined) {
  41614. animation.setEasingFunction(easingFunction);
  41615. }
  41616. return animation;
  41617. };
  41618. /**
  41619. * Sets up an animation.
  41620. * @param property the property to animate
  41621. * @param animationType the animation type to apply
  41622. * @param easingFunction the easing function used in the animation
  41623. * @returns The created animation
  41624. */
  41625. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41626. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41627. animation.setEasingFunction(easingFunction);
  41628. return animation;
  41629. };
  41630. /**
  41631. * Create and start an animation on a node
  41632. * @param {string} name defines the name of the global animation that will be run on all nodes
  41633. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41634. * @param {string} targetProperty defines property to animate
  41635. * @param {number} framePerSecond defines the number of frame per second yo use
  41636. * @param {number} totalFrame defines the number of frames in total
  41637. * @param {any} from defines the initial value
  41638. * @param {any} to defines the final value
  41639. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41640. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41641. * @param onAnimationEnd defines the callback to call when animation end
  41642. * @returns the animatable created for this animation
  41643. */
  41644. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41645. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41646. if (!animation) {
  41647. return null;
  41648. }
  41649. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41650. };
  41651. /**
  41652. * Create and start an animation on a node and its descendants
  41653. * @param {string} name defines the name of the global animation that will be run on all nodes
  41654. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41655. * @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.
  41656. * @param {string} targetProperty defines property to animate
  41657. * @param {number} framePerSecond defines the number of frame per second yo use
  41658. * @param {number} totalFrame defines the number of frames in total
  41659. * @param {any} from defines the initial value
  41660. * @param {any} to defines the final value
  41661. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41662. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41663. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41664. * @returns the list of animatables created for all nodes
  41665. * @example https://www.babylonjs-playground.com/#MH0VLI
  41666. */
  41667. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41668. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41669. if (!animation) {
  41670. return null;
  41671. }
  41672. var scene = node.getScene();
  41673. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41674. };
  41675. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41676. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41677. if (!animation) {
  41678. return null;
  41679. }
  41680. node.animations.push(animation);
  41681. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41682. };
  41683. /**
  41684. * Transition property of the Camera to the target Value.
  41685. * @param property The property to transition
  41686. * @param targetValue The target Value of the property
  41687. * @param host The object where the property to animate belongs
  41688. * @param scene Scene used to run the animation
  41689. * @param frameRate Framerate (in frame/s) to use
  41690. * @param transition The transition type we want to use
  41691. * @param duration The duration of the animation, in milliseconds
  41692. * @param onAnimationEnd Call back trigger at the end of the animation.
  41693. */
  41694. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41695. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41696. if (duration <= 0) {
  41697. host[property] = targetValue;
  41698. if (onAnimationEnd) {
  41699. onAnimationEnd();
  41700. }
  41701. return null;
  41702. }
  41703. var endFrame = frameRate * (duration / 1000);
  41704. transition.setKeys([{
  41705. frame: 0,
  41706. value: host[property].clone ? host[property].clone() : host[property]
  41707. },
  41708. {
  41709. frame: endFrame,
  41710. value: targetValue
  41711. }]);
  41712. if (!host.animations) {
  41713. host.animations = [];
  41714. }
  41715. host.animations.push(transition);
  41716. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41717. animation.onAnimationEnd = onAnimationEnd;
  41718. return animation;
  41719. };
  41720. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41721. /**
  41722. * Return the array of runtime animations currently using this animation
  41723. */
  41724. get: function () {
  41725. return this._runtimeAnimations;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41731. get: function () {
  41732. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41733. var runtimeAnimation = _a[_i];
  41734. if (!runtimeAnimation.isStopped) {
  41735. return true;
  41736. }
  41737. }
  41738. return false;
  41739. },
  41740. enumerable: true,
  41741. configurable: true
  41742. });
  41743. // Methods
  41744. /**
  41745. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41746. */
  41747. Animation.prototype.toString = function (fullDetails) {
  41748. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41749. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41750. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41751. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41752. if (fullDetails) {
  41753. ret += ", Ranges: {";
  41754. var first = true;
  41755. for (var name in this._ranges) {
  41756. if (first) {
  41757. ret += ", ";
  41758. first = false;
  41759. }
  41760. ret += name;
  41761. }
  41762. ret += "}";
  41763. }
  41764. return ret;
  41765. };
  41766. /**
  41767. * Add an event to this animation.
  41768. */
  41769. Animation.prototype.addEvent = function (event) {
  41770. this._events.push(event);
  41771. };
  41772. /**
  41773. * Remove all events found at the given frame
  41774. * @param frame
  41775. */
  41776. Animation.prototype.removeEvents = function (frame) {
  41777. for (var index = 0; index < this._events.length; index++) {
  41778. if (this._events[index].frame === frame) {
  41779. this._events.splice(index, 1);
  41780. index--;
  41781. }
  41782. }
  41783. };
  41784. Animation.prototype.getEvents = function () {
  41785. return this._events;
  41786. };
  41787. Animation.prototype.createRange = function (name, from, to) {
  41788. // check name not already in use; could happen for bones after serialized
  41789. if (!this._ranges[name]) {
  41790. this._ranges[name] = new AnimationRange(name, from, to);
  41791. }
  41792. };
  41793. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41794. if (deleteFrames === void 0) { deleteFrames = true; }
  41795. var range = this._ranges[name];
  41796. if (!range) {
  41797. return;
  41798. }
  41799. if (deleteFrames) {
  41800. var from = range.from;
  41801. var to = range.to;
  41802. // this loop MUST go high to low for multiple splices to work
  41803. for (var key = this._keys.length - 1; key >= 0; key--) {
  41804. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41805. this._keys.splice(key, 1);
  41806. }
  41807. }
  41808. }
  41809. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41810. };
  41811. Animation.prototype.getRange = function (name) {
  41812. return this._ranges[name];
  41813. };
  41814. Animation.prototype.getKeys = function () {
  41815. return this._keys;
  41816. };
  41817. Animation.prototype.getHighestFrame = function () {
  41818. var ret = 0;
  41819. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41820. if (ret < this._keys[key].frame) {
  41821. ret = this._keys[key].frame;
  41822. }
  41823. }
  41824. return ret;
  41825. };
  41826. Animation.prototype.getEasingFunction = function () {
  41827. return this._easingFunction;
  41828. };
  41829. Animation.prototype.setEasingFunction = function (easingFunction) {
  41830. this._easingFunction = easingFunction;
  41831. };
  41832. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41833. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41834. };
  41835. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41836. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41837. };
  41838. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41839. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41840. };
  41841. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41842. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41843. };
  41844. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41845. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41846. };
  41847. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41848. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41849. };
  41850. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41851. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41852. };
  41853. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41854. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41855. };
  41856. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41857. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41858. };
  41859. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41860. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41861. };
  41862. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41863. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41864. };
  41865. Animation.prototype.clone = function () {
  41866. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41867. clone.enableBlending = this.enableBlending;
  41868. clone.blendingSpeed = this.blendingSpeed;
  41869. if (this._keys) {
  41870. clone.setKeys(this._keys);
  41871. }
  41872. if (this._ranges) {
  41873. clone._ranges = {};
  41874. for (var name in this._ranges) {
  41875. var range = this._ranges[name];
  41876. if (!range) {
  41877. continue;
  41878. }
  41879. clone._ranges[name] = range.clone();
  41880. }
  41881. }
  41882. return clone;
  41883. };
  41884. Animation.prototype.setKeys = function (values) {
  41885. this._keys = values.slice(0);
  41886. };
  41887. Animation.prototype.serialize = function () {
  41888. var serializationObject = {};
  41889. serializationObject.name = this.name;
  41890. serializationObject.property = this.targetProperty;
  41891. serializationObject.framePerSecond = this.framePerSecond;
  41892. serializationObject.dataType = this.dataType;
  41893. serializationObject.loopBehavior = this.loopMode;
  41894. serializationObject.enableBlending = this.enableBlending;
  41895. serializationObject.blendingSpeed = this.blendingSpeed;
  41896. var dataType = this.dataType;
  41897. serializationObject.keys = [];
  41898. var keys = this.getKeys();
  41899. for (var index = 0; index < keys.length; index++) {
  41900. var animationKey = keys[index];
  41901. var key = {};
  41902. key.frame = animationKey.frame;
  41903. switch (dataType) {
  41904. case Animation.ANIMATIONTYPE_FLOAT:
  41905. key.values = [animationKey.value];
  41906. break;
  41907. case Animation.ANIMATIONTYPE_QUATERNION:
  41908. case Animation.ANIMATIONTYPE_MATRIX:
  41909. case Animation.ANIMATIONTYPE_VECTOR3:
  41910. case Animation.ANIMATIONTYPE_COLOR3:
  41911. key.values = animationKey.value.asArray();
  41912. break;
  41913. }
  41914. serializationObject.keys.push(key);
  41915. }
  41916. serializationObject.ranges = [];
  41917. for (var name in this._ranges) {
  41918. var source = this._ranges[name];
  41919. if (!source) {
  41920. continue;
  41921. }
  41922. var range = {};
  41923. range.name = name;
  41924. range.from = source.from;
  41925. range.to = source.to;
  41926. serializationObject.ranges.push(range);
  41927. }
  41928. return serializationObject;
  41929. };
  41930. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41931. get: function () {
  41932. return Animation._ANIMATIONTYPE_FLOAT;
  41933. },
  41934. enumerable: true,
  41935. configurable: true
  41936. });
  41937. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41938. get: function () {
  41939. return Animation._ANIMATIONTYPE_VECTOR3;
  41940. },
  41941. enumerable: true,
  41942. configurable: true
  41943. });
  41944. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41945. get: function () {
  41946. return Animation._ANIMATIONTYPE_VECTOR2;
  41947. },
  41948. enumerable: true,
  41949. configurable: true
  41950. });
  41951. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41952. get: function () {
  41953. return Animation._ANIMATIONTYPE_SIZE;
  41954. },
  41955. enumerable: true,
  41956. configurable: true
  41957. });
  41958. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41959. get: function () {
  41960. return Animation._ANIMATIONTYPE_QUATERNION;
  41961. },
  41962. enumerable: true,
  41963. configurable: true
  41964. });
  41965. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41966. get: function () {
  41967. return Animation._ANIMATIONTYPE_MATRIX;
  41968. },
  41969. enumerable: true,
  41970. configurable: true
  41971. });
  41972. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41973. get: function () {
  41974. return Animation._ANIMATIONTYPE_COLOR3;
  41975. },
  41976. enumerable: true,
  41977. configurable: true
  41978. });
  41979. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41980. get: function () {
  41981. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41982. },
  41983. enumerable: true,
  41984. configurable: true
  41985. });
  41986. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41987. get: function () {
  41988. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41989. },
  41990. enumerable: true,
  41991. configurable: true
  41992. });
  41993. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41994. get: function () {
  41995. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41996. },
  41997. enumerable: true,
  41998. configurable: true
  41999. });
  42000. Animation.Parse = function (parsedAnimation) {
  42001. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42002. var dataType = parsedAnimation.dataType;
  42003. var keys = [];
  42004. var data;
  42005. var index;
  42006. if (parsedAnimation.enableBlending) {
  42007. animation.enableBlending = parsedAnimation.enableBlending;
  42008. }
  42009. if (parsedAnimation.blendingSpeed) {
  42010. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42011. }
  42012. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42013. var key = parsedAnimation.keys[index];
  42014. var inTangent;
  42015. var outTangent;
  42016. switch (dataType) {
  42017. case Animation.ANIMATIONTYPE_FLOAT:
  42018. data = key.values[0];
  42019. if (key.values.length >= 1) {
  42020. inTangent = key.values[1];
  42021. }
  42022. if (key.values.length >= 2) {
  42023. outTangent = key.values[2];
  42024. }
  42025. break;
  42026. case Animation.ANIMATIONTYPE_QUATERNION:
  42027. data = BABYLON.Quaternion.FromArray(key.values);
  42028. if (key.values.length >= 8) {
  42029. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42030. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42031. inTangent = _inTangent;
  42032. }
  42033. }
  42034. if (key.values.length >= 12) {
  42035. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42036. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42037. outTangent = _outTangent;
  42038. }
  42039. }
  42040. break;
  42041. case Animation.ANIMATIONTYPE_MATRIX:
  42042. data = BABYLON.Matrix.FromArray(key.values);
  42043. break;
  42044. case Animation.ANIMATIONTYPE_COLOR3:
  42045. data = BABYLON.Color3.FromArray(key.values);
  42046. break;
  42047. case Animation.ANIMATIONTYPE_VECTOR3:
  42048. default:
  42049. data = BABYLON.Vector3.FromArray(key.values);
  42050. break;
  42051. }
  42052. var keyData = {};
  42053. keyData.frame = key.frame;
  42054. keyData.value = data;
  42055. if (inTangent != undefined) {
  42056. keyData.inTangent = inTangent;
  42057. }
  42058. if (outTangent != undefined) {
  42059. keyData.outTangent = outTangent;
  42060. }
  42061. keys.push(keyData);
  42062. }
  42063. animation.setKeys(keys);
  42064. if (parsedAnimation.ranges) {
  42065. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42066. data = parsedAnimation.ranges[index];
  42067. animation.createRange(data.name, data.from, data.to);
  42068. }
  42069. }
  42070. return animation;
  42071. };
  42072. Animation.AppendSerializedAnimations = function (source, destination) {
  42073. if (source.animations) {
  42074. destination.animations = [];
  42075. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42076. var animation = source.animations[animationIndex];
  42077. destination.animations.push(animation.serialize());
  42078. }
  42079. }
  42080. };
  42081. Animation.AllowMatricesInterpolation = false;
  42082. // Statics
  42083. Animation._ANIMATIONTYPE_FLOAT = 0;
  42084. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42085. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42086. Animation._ANIMATIONTYPE_MATRIX = 3;
  42087. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42088. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42089. Animation._ANIMATIONTYPE_SIZE = 6;
  42090. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42091. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42092. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42093. return Animation;
  42094. }());
  42095. BABYLON.Animation = Animation;
  42096. })(BABYLON || (BABYLON = {}));
  42097. //# sourceMappingURL=babylon.animation.js.map
  42098. var BABYLON;
  42099. (function (BABYLON) {
  42100. /**
  42101. * This class defines the direct association between an animation and a target
  42102. */
  42103. var TargetedAnimation = /** @class */ (function () {
  42104. function TargetedAnimation() {
  42105. }
  42106. return TargetedAnimation;
  42107. }());
  42108. BABYLON.TargetedAnimation = TargetedAnimation;
  42109. /**
  42110. * Use this class to create coordinated animations on multiple targets
  42111. */
  42112. var AnimationGroup = /** @class */ (function () {
  42113. function AnimationGroup(name, scene) {
  42114. if (scene === void 0) { scene = null; }
  42115. this.name = name;
  42116. this._targetedAnimations = new Array();
  42117. this._animatables = new Array();
  42118. this._from = Number.MAX_VALUE;
  42119. this._to = Number.MIN_VALUE;
  42120. this._speedRatio = 1;
  42121. this.onAnimationEndObservable = new BABYLON.Observable();
  42122. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42123. this._scene.animationGroups.push(this);
  42124. }
  42125. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42126. /**
  42127. * Define if the animations are started
  42128. */
  42129. get: function () {
  42130. return this._isStarted;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42136. /**
  42137. * Gets or sets the speed ratio to use for all animations
  42138. */
  42139. get: function () {
  42140. return this._speedRatio;
  42141. },
  42142. /**
  42143. * Gets or sets the speed ratio to use for all animations
  42144. */
  42145. set: function (value) {
  42146. if (this._speedRatio === value) {
  42147. return;
  42148. }
  42149. this._speedRatio = value;
  42150. for (var index = 0; index < this._animatables.length; index++) {
  42151. var animatable = this._animatables[index];
  42152. animatable.speedRatio = this._speedRatio;
  42153. }
  42154. },
  42155. enumerable: true,
  42156. configurable: true
  42157. });
  42158. /**
  42159. * Add an animation (with its target) in the group
  42160. * @param animation defines the animation we want to add
  42161. * @param target defines the target of the animation
  42162. * @returns the {BABYLON.TargetedAnimation} object
  42163. */
  42164. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42165. var targetedAnimation = {
  42166. animation: animation,
  42167. target: target
  42168. };
  42169. var keys = animation.getKeys();
  42170. if (this._from > keys[0].frame) {
  42171. this._from = keys[0].frame;
  42172. }
  42173. if (this._to < keys[keys.length - 1].frame) {
  42174. this._to = keys[keys.length - 1].frame;
  42175. }
  42176. this._targetedAnimations.push(targetedAnimation);
  42177. return targetedAnimation;
  42178. };
  42179. /**
  42180. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42181. * It can add constant keys at begin or end
  42182. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  42183. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  42184. */
  42185. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42186. beginFrame = Math.min(beginFrame, this._from);
  42187. endFrame = Math.min(endFrame, this._to);
  42188. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42189. var targetedAnimation = this._targetedAnimations[index];
  42190. var keys = targetedAnimation.animation.getKeys();
  42191. var startKey = keys[0];
  42192. var endKey = keys[keys.length - 1];
  42193. if (startKey.frame > beginFrame) {
  42194. var newKey = {
  42195. frame: beginFrame,
  42196. value: startKey.value,
  42197. inTangent: startKey.inTangent,
  42198. outTangent: startKey.outTangent
  42199. };
  42200. keys.splice(0, 0, newKey);
  42201. }
  42202. if (endKey.frame < endFrame) {
  42203. var newKey = {
  42204. frame: endFrame,
  42205. value: endKey.value,
  42206. inTangent: startKey.outTangent,
  42207. outTangent: startKey.outTangent
  42208. };
  42209. keys.push(newKey);
  42210. }
  42211. }
  42212. return this;
  42213. };
  42214. /**
  42215. * Start all animations on given targets
  42216. * @param loop defines if animations must loop
  42217. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42218. */
  42219. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42220. var _this = this;
  42221. if (loop === void 0) { loop = false; }
  42222. if (speedRatio === void 0) { speedRatio = 1; }
  42223. if (this._isStarted || this._targetedAnimations.length === 0) {
  42224. return this;
  42225. }
  42226. var _loop_1 = function () {
  42227. var targetedAnimation = this_1._targetedAnimations[index];
  42228. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42229. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42230. }));
  42231. };
  42232. var this_1 = this;
  42233. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42234. _loop_1();
  42235. }
  42236. this._speedRatio = speedRatio;
  42237. this._isStarted = true;
  42238. return this;
  42239. };
  42240. /**
  42241. * Pause all animations
  42242. */
  42243. AnimationGroup.prototype.pause = function () {
  42244. if (!this._isStarted) {
  42245. return this;
  42246. }
  42247. for (var index = 0; index < this._animatables.length; index++) {
  42248. var animatable = this._animatables[index];
  42249. animatable.pause();
  42250. }
  42251. return this;
  42252. };
  42253. /**
  42254. * Play all animations to initial state
  42255. * This function will start() the animations if they were not started or will restart() them if they were paused
  42256. * @param loop defines if animations must loop
  42257. */
  42258. AnimationGroup.prototype.play = function (loop) {
  42259. if (this.isStarted) {
  42260. if (loop !== undefined) {
  42261. for (var index = 0; index < this._animatables.length; index++) {
  42262. var animatable = this._animatables[index];
  42263. animatable.loopAnimation = loop;
  42264. }
  42265. }
  42266. this.restart();
  42267. }
  42268. else {
  42269. this.start(loop, this._speedRatio);
  42270. }
  42271. return this;
  42272. };
  42273. /**
  42274. * Reset all animations to initial state
  42275. */
  42276. AnimationGroup.prototype.reset = function () {
  42277. if (!this._isStarted) {
  42278. return this;
  42279. }
  42280. for (var index = 0; index < this._animatables.length; index++) {
  42281. var animatable = this._animatables[index];
  42282. animatable.reset();
  42283. }
  42284. return this;
  42285. };
  42286. /**
  42287. * Restart animations from key 0
  42288. */
  42289. AnimationGroup.prototype.restart = function () {
  42290. if (!this._isStarted) {
  42291. return this;
  42292. }
  42293. for (var index = 0; index < this._animatables.length; index++) {
  42294. var animatable = this._animatables[index];
  42295. animatable.restart();
  42296. }
  42297. return this;
  42298. };
  42299. /**
  42300. * Stop all animations
  42301. */
  42302. AnimationGroup.prototype.stop = function () {
  42303. if (!this._isStarted) {
  42304. return this;
  42305. }
  42306. for (var index = 0; index < this._animatables.length; index++) {
  42307. var animatable = this._animatables[index];
  42308. animatable.stop();
  42309. }
  42310. this._isStarted = false;
  42311. return this;
  42312. };
  42313. /**
  42314. * Dispose all associated resources
  42315. */
  42316. AnimationGroup.prototype.dispose = function () {
  42317. this._targetedAnimations = [];
  42318. this._animatables = [];
  42319. var index = this._scene.animationGroups.indexOf(this);
  42320. if (index > -1) {
  42321. this._scene.animationGroups.splice(index, 1);
  42322. }
  42323. };
  42324. return AnimationGroup;
  42325. }());
  42326. BABYLON.AnimationGroup = AnimationGroup;
  42327. })(BABYLON || (BABYLON = {}));
  42328. //# sourceMappingURL=babylon.animationGroup.js.map
  42329. var BABYLON;
  42330. (function (BABYLON) {
  42331. var RuntimeAnimation = /** @class */ (function () {
  42332. function RuntimeAnimation(target, animation) {
  42333. this._offsetsCache = {};
  42334. this._highLimitsCache = {};
  42335. this._stopped = false;
  42336. this._blendingFactor = 0;
  42337. this._ratioOffset = 0;
  42338. this._animation = animation;
  42339. this._target = target;
  42340. animation._runtimeAnimations.push(this);
  42341. }
  42342. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42343. get: function () {
  42344. return this._animation;
  42345. },
  42346. enumerable: true,
  42347. configurable: true
  42348. });
  42349. RuntimeAnimation.prototype.reset = function () {
  42350. this._offsetsCache = {};
  42351. this._highLimitsCache = {};
  42352. this.currentFrame = 0;
  42353. this._blendingFactor = 0;
  42354. this._originalBlendValue = null;
  42355. };
  42356. RuntimeAnimation.prototype.isStopped = function () {
  42357. return this._stopped;
  42358. };
  42359. RuntimeAnimation.prototype.dispose = function () {
  42360. var index = this._animation.runtimeAnimations.indexOf(this);
  42361. if (index > -1) {
  42362. this._animation.runtimeAnimations.splice(index, 1);
  42363. }
  42364. };
  42365. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42366. if (typeof value === "function") {
  42367. return value();
  42368. }
  42369. return value;
  42370. };
  42371. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42372. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42373. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42374. }
  42375. this.currentFrame = currentFrame;
  42376. var keys = this._animation.getKeys();
  42377. // Try to get a hash to find the right key
  42378. 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));
  42379. if (keys[startKeyIndex].frame >= currentFrame) {
  42380. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42381. startKeyIndex--;
  42382. }
  42383. }
  42384. for (var key = startKeyIndex; key < keys.length; key++) {
  42385. var endKey = keys[key + 1];
  42386. if (endKey.frame >= currentFrame) {
  42387. var startKey = keys[key];
  42388. var startValue = this._getKeyValue(startKey.value);
  42389. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42390. return startValue;
  42391. }
  42392. var endValue = this._getKeyValue(endKey.value);
  42393. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42394. var frameDelta = endKey.frame - startKey.frame;
  42395. // gradient : percent of currentFrame between the frame inf and the frame sup
  42396. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42397. // check for easingFunction and correction of gradient
  42398. var easingFunction = this._animation.getEasingFunction();
  42399. if (easingFunction != null) {
  42400. gradient = easingFunction.ease(gradient);
  42401. }
  42402. switch (this._animation.dataType) {
  42403. // Float
  42404. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42405. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42406. switch (loopMode) {
  42407. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42408. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42409. return floatValue;
  42410. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42411. return offsetValue * repeatCount + floatValue;
  42412. }
  42413. break;
  42414. // Quaternion
  42415. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42416. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42417. switch (loopMode) {
  42418. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42419. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42420. return quatValue;
  42421. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42422. return quatValue.add(offsetValue.scale(repeatCount));
  42423. }
  42424. return quatValue;
  42425. // Vector3
  42426. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42427. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42428. switch (loopMode) {
  42429. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42430. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42431. return vec3Value;
  42432. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42433. return vec3Value.add(offsetValue.scale(repeatCount));
  42434. }
  42435. // Vector2
  42436. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42437. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42438. switch (loopMode) {
  42439. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42440. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42441. return vec2Value;
  42442. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42443. return vec2Value.add(offsetValue.scale(repeatCount));
  42444. }
  42445. // Size
  42446. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42447. switch (loopMode) {
  42448. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42449. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42450. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42451. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42452. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42453. }
  42454. // Color3
  42455. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42456. switch (loopMode) {
  42457. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42458. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42459. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42460. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42461. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42462. }
  42463. // Matrix
  42464. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42465. switch (loopMode) {
  42466. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42467. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42468. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42469. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42470. }
  42471. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42472. return startValue;
  42473. }
  42474. default:
  42475. break;
  42476. }
  42477. break;
  42478. }
  42479. }
  42480. return this._getKeyValue(keys[keys.length - 1].value);
  42481. };
  42482. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42483. if (blend === void 0) { blend = false; }
  42484. // Set value
  42485. var path;
  42486. var destination;
  42487. var targetPropertyPath = this._animation.targetPropertyPath;
  42488. if (targetPropertyPath.length > 1) {
  42489. var property = this._target[targetPropertyPath[0]];
  42490. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42491. property = property[targetPropertyPath[index]];
  42492. }
  42493. path = targetPropertyPath[targetPropertyPath.length - 1];
  42494. destination = property;
  42495. }
  42496. else {
  42497. path = targetPropertyPath[0];
  42498. destination = this._target;
  42499. }
  42500. // Blending
  42501. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42502. if (!this._originalBlendValue) {
  42503. if (destination[path].clone) {
  42504. this._originalBlendValue = destination[path].clone();
  42505. }
  42506. else {
  42507. this._originalBlendValue = destination[path];
  42508. }
  42509. }
  42510. if (this._originalBlendValue.prototype) {
  42511. if (this._originalBlendValue.prototype.Lerp) {
  42512. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42513. }
  42514. else {
  42515. destination[path] = currentValue;
  42516. }
  42517. }
  42518. else if (this._originalBlendValue.m) {
  42519. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42520. }
  42521. else {
  42522. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42523. }
  42524. this._blendingFactor += this._animation.blendingSpeed;
  42525. }
  42526. else {
  42527. destination[path] = currentValue;
  42528. }
  42529. if (this._target.markAsDirty) {
  42530. this._target.markAsDirty(this._animation.targetProperty);
  42531. }
  42532. };
  42533. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42534. var keys = this._animation.getKeys();
  42535. if (frame < keys[0].frame) {
  42536. frame = keys[0].frame;
  42537. }
  42538. else if (frame > keys[keys.length - 1].frame) {
  42539. frame = keys[keys.length - 1].frame;
  42540. }
  42541. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42542. this.setValue(currentValue);
  42543. };
  42544. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42545. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42546. this._ratioOffset = this._previousRatio - newRatio;
  42547. };
  42548. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42549. if (blend === void 0) { blend = false; }
  42550. var targetPropertyPath = this._animation.targetPropertyPath;
  42551. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42552. this._stopped = true;
  42553. return false;
  42554. }
  42555. var returnValue = true;
  42556. var keys = this._animation.getKeys();
  42557. // Adding a start key at frame 0 if missing
  42558. if (keys[0].frame !== 0) {
  42559. var newKey = { frame: 0, value: keys[0].value };
  42560. keys.splice(0, 0, newKey);
  42561. }
  42562. // Check limits
  42563. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42564. from = keys[0].frame;
  42565. }
  42566. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42567. to = keys[keys.length - 1].frame;
  42568. }
  42569. //to and from cannot be the same key
  42570. if (from === to) {
  42571. if (from > keys[0].frame) {
  42572. from--;
  42573. }
  42574. else if (to < keys[keys.length - 1].frame) {
  42575. to++;
  42576. }
  42577. }
  42578. // Compute ratio
  42579. var range = to - from;
  42580. var offsetValue;
  42581. // ratio represents the frame delta between from and to
  42582. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42583. var highLimitValue = 0;
  42584. this._previousDelay = delay;
  42585. this._previousRatio = ratio;
  42586. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42587. returnValue = false;
  42588. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42589. }
  42590. else {
  42591. // Get max value if required
  42592. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42593. var keyOffset = to.toString() + from.toString();
  42594. if (!this._offsetsCache[keyOffset]) {
  42595. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42596. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42597. switch (this._animation.dataType) {
  42598. // Float
  42599. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42600. this._offsetsCache[keyOffset] = toValue - fromValue;
  42601. break;
  42602. // Quaternion
  42603. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42604. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42605. break;
  42606. // Vector3
  42607. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42608. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42609. // Vector2
  42610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42611. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42612. // Size
  42613. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42614. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42615. // Color3
  42616. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42617. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42618. default:
  42619. break;
  42620. }
  42621. this._highLimitsCache[keyOffset] = toValue;
  42622. }
  42623. highLimitValue = this._highLimitsCache[keyOffset];
  42624. offsetValue = this._offsetsCache[keyOffset];
  42625. }
  42626. }
  42627. if (offsetValue === undefined) {
  42628. switch (this._animation.dataType) {
  42629. // Float
  42630. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42631. offsetValue = 0;
  42632. break;
  42633. // Quaternion
  42634. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42635. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42636. break;
  42637. // Vector3
  42638. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42639. offsetValue = BABYLON.Vector3.Zero();
  42640. break;
  42641. // Vector2
  42642. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42643. offsetValue = BABYLON.Vector2.Zero();
  42644. break;
  42645. // Size
  42646. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42647. offsetValue = BABYLON.Size.Zero();
  42648. break;
  42649. // Color3
  42650. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42651. offsetValue = BABYLON.Color3.Black();
  42652. }
  42653. }
  42654. // Compute value
  42655. var repeatCount = (ratio / range) >> 0;
  42656. var currentFrame = returnValue ? from + ratio % range : to;
  42657. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42658. // Set value
  42659. this.setValue(currentValue);
  42660. // Check events
  42661. var events = this._animation.getEvents();
  42662. for (var index = 0; index < events.length; index++) {
  42663. // Make sure current frame has passed event frame and that event frame is within the current range
  42664. // Also, handle both forward and reverse animations
  42665. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42666. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42667. var event = events[index];
  42668. if (!event.isDone) {
  42669. // If event should be done only once, remove it.
  42670. if (event.onlyOnce) {
  42671. events.splice(index, 1);
  42672. index--;
  42673. }
  42674. event.isDone = true;
  42675. event.action();
  42676. } // Don't do anything if the event has already be done.
  42677. }
  42678. else if (events[index].isDone && !events[index].onlyOnce) {
  42679. // reset event, the animation is looping
  42680. events[index].isDone = false;
  42681. }
  42682. }
  42683. if (!returnValue) {
  42684. this._stopped = true;
  42685. }
  42686. return returnValue;
  42687. };
  42688. return RuntimeAnimation;
  42689. }());
  42690. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42691. })(BABYLON || (BABYLON = {}));
  42692. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42693. var BABYLON;
  42694. (function (BABYLON) {
  42695. var Animatable = /** @class */ (function () {
  42696. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42697. if (fromFrame === void 0) { fromFrame = 0; }
  42698. if (toFrame === void 0) { toFrame = 100; }
  42699. if (loopAnimation === void 0) { loopAnimation = false; }
  42700. if (speedRatio === void 0) { speedRatio = 1.0; }
  42701. this.target = target;
  42702. this.fromFrame = fromFrame;
  42703. this.toFrame = toFrame;
  42704. this.loopAnimation = loopAnimation;
  42705. this.onAnimationEnd = onAnimationEnd;
  42706. this._localDelayOffset = null;
  42707. this._pausedDelay = null;
  42708. this._runtimeAnimations = new Array();
  42709. this._paused = false;
  42710. this._speedRatio = 1;
  42711. this.animationStarted = false;
  42712. if (animations) {
  42713. this.appendAnimations(target, animations);
  42714. }
  42715. this._speedRatio = speedRatio;
  42716. this._scene = scene;
  42717. scene._activeAnimatables.push(this);
  42718. }
  42719. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42720. get: function () {
  42721. return this._speedRatio;
  42722. },
  42723. set: function (value) {
  42724. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42725. var animation = this._runtimeAnimations[index];
  42726. animation._prepareForSpeedRatioChange(value);
  42727. }
  42728. this._speedRatio = value;
  42729. },
  42730. enumerable: true,
  42731. configurable: true
  42732. });
  42733. // Methods
  42734. Animatable.prototype.getAnimations = function () {
  42735. return this._runtimeAnimations;
  42736. };
  42737. Animatable.prototype.appendAnimations = function (target, animations) {
  42738. for (var index = 0; index < animations.length; index++) {
  42739. var animation = animations[index];
  42740. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  42741. }
  42742. };
  42743. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  42744. var runtimeAnimations = this._runtimeAnimations;
  42745. for (var index = 0; index < runtimeAnimations.length; index++) {
  42746. if (runtimeAnimations[index].animation.targetProperty === property) {
  42747. return runtimeAnimations[index].animation;
  42748. }
  42749. }
  42750. return null;
  42751. };
  42752. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  42753. var runtimeAnimations = this._runtimeAnimations;
  42754. for (var index = 0; index < runtimeAnimations.length; index++) {
  42755. if (runtimeAnimations[index].animation.targetProperty === property) {
  42756. return runtimeAnimations[index];
  42757. }
  42758. }
  42759. return null;
  42760. };
  42761. Animatable.prototype.reset = function () {
  42762. var runtimeAnimations = this._runtimeAnimations;
  42763. for (var index = 0; index < runtimeAnimations.length; index++) {
  42764. runtimeAnimations[index].reset();
  42765. }
  42766. // Reset to original value
  42767. for (index = 0; index < runtimeAnimations.length; index++) {
  42768. var animation = runtimeAnimations[index];
  42769. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  42770. }
  42771. this._localDelayOffset = null;
  42772. this._pausedDelay = null;
  42773. };
  42774. Animatable.prototype.enableBlending = function (blendingSpeed) {
  42775. var runtimeAnimations = this._runtimeAnimations;
  42776. for (var index = 0; index < runtimeAnimations.length; index++) {
  42777. runtimeAnimations[index].animation.enableBlending = true;
  42778. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42779. }
  42780. };
  42781. Animatable.prototype.disableBlending = function () {
  42782. var runtimeAnimations = this._runtimeAnimations;
  42783. for (var index = 0; index < runtimeAnimations.length; index++) {
  42784. runtimeAnimations[index].animation.enableBlending = false;
  42785. }
  42786. };
  42787. Animatable.prototype.goToFrame = function (frame) {
  42788. var runtimeAnimations = this._runtimeAnimations;
  42789. if (runtimeAnimations[0]) {
  42790. var fps = runtimeAnimations[0].animation.framePerSecond;
  42791. var currentFrame = runtimeAnimations[0].currentFrame;
  42792. var adjustTime = frame - currentFrame;
  42793. var delay = adjustTime * 1000 / fps;
  42794. if (this._localDelayOffset === null) {
  42795. this._localDelayOffset = 0;
  42796. }
  42797. this._localDelayOffset -= delay;
  42798. }
  42799. for (var index = 0; index < runtimeAnimations.length; index++) {
  42800. runtimeAnimations[index].goToFrame(frame);
  42801. }
  42802. };
  42803. Animatable.prototype.pause = function () {
  42804. if (this._paused) {
  42805. return;
  42806. }
  42807. this._paused = true;
  42808. };
  42809. Animatable.prototype.restart = function () {
  42810. this._paused = false;
  42811. };
  42812. Animatable.prototype.stop = function (animationName) {
  42813. if (animationName) {
  42814. var idx = this._scene._activeAnimatables.indexOf(this);
  42815. if (idx > -1) {
  42816. var runtimeAnimations = this._runtimeAnimations;
  42817. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42818. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42819. continue;
  42820. }
  42821. runtimeAnimations[index].dispose();
  42822. runtimeAnimations.splice(index, 1);
  42823. }
  42824. if (runtimeAnimations.length == 0) {
  42825. this._scene._activeAnimatables.splice(idx, 1);
  42826. if (this.onAnimationEnd) {
  42827. this.onAnimationEnd();
  42828. }
  42829. }
  42830. }
  42831. }
  42832. else {
  42833. var index = this._scene._activeAnimatables.indexOf(this);
  42834. if (index > -1) {
  42835. this._scene._activeAnimatables.splice(index, 1);
  42836. var runtimeAnimations = this._runtimeAnimations;
  42837. for (var index = 0; index < runtimeAnimations.length; index++) {
  42838. runtimeAnimations[index].dispose();
  42839. }
  42840. if (this.onAnimationEnd) {
  42841. this.onAnimationEnd();
  42842. }
  42843. }
  42844. }
  42845. };
  42846. Animatable.prototype._animate = function (delay) {
  42847. if (this._paused) {
  42848. this.animationStarted = false;
  42849. if (this._pausedDelay === null) {
  42850. this._pausedDelay = delay;
  42851. }
  42852. return true;
  42853. }
  42854. if (this._localDelayOffset === null) {
  42855. this._localDelayOffset = delay;
  42856. }
  42857. else if (this._pausedDelay !== null) {
  42858. this._localDelayOffset += delay - this._pausedDelay;
  42859. this._pausedDelay = null;
  42860. }
  42861. // Animating
  42862. var running = false;
  42863. var runtimeAnimations = this._runtimeAnimations;
  42864. var index;
  42865. for (index = 0; index < runtimeAnimations.length; index++) {
  42866. var animation = runtimeAnimations[index];
  42867. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42868. running = running || isRunning;
  42869. }
  42870. this.animationStarted = running;
  42871. if (!running) {
  42872. // Remove from active animatables
  42873. index = this._scene._activeAnimatables.indexOf(this);
  42874. this._scene._activeAnimatables.splice(index, 1);
  42875. // Dispose all runtime animations
  42876. for (index = 0; index < runtimeAnimations.length; index++) {
  42877. runtimeAnimations[index].dispose();
  42878. }
  42879. }
  42880. if (!running && this.onAnimationEnd) {
  42881. this.onAnimationEnd();
  42882. this.onAnimationEnd = null;
  42883. }
  42884. return running;
  42885. };
  42886. return Animatable;
  42887. }());
  42888. BABYLON.Animatable = Animatable;
  42889. })(BABYLON || (BABYLON = {}));
  42890. //# sourceMappingURL=babylon.animatable.js.map
  42891. var BABYLON;
  42892. (function (BABYLON) {
  42893. var EasingFunction = /** @class */ (function () {
  42894. function EasingFunction() {
  42895. // Properties
  42896. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42897. }
  42898. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42899. get: function () {
  42900. return EasingFunction._EASINGMODE_EASEIN;
  42901. },
  42902. enumerable: true,
  42903. configurable: true
  42904. });
  42905. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42906. get: function () {
  42907. return EasingFunction._EASINGMODE_EASEOUT;
  42908. },
  42909. enumerable: true,
  42910. configurable: true
  42911. });
  42912. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42913. get: function () {
  42914. return EasingFunction._EASINGMODE_EASEINOUT;
  42915. },
  42916. enumerable: true,
  42917. configurable: true
  42918. });
  42919. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42920. var n = Math.min(Math.max(easingMode, 0), 2);
  42921. this._easingMode = n;
  42922. };
  42923. EasingFunction.prototype.getEasingMode = function () {
  42924. return this._easingMode;
  42925. };
  42926. EasingFunction.prototype.easeInCore = function (gradient) {
  42927. throw new Error('You must implement this method');
  42928. };
  42929. EasingFunction.prototype.ease = function (gradient) {
  42930. switch (this._easingMode) {
  42931. case EasingFunction.EASINGMODE_EASEIN:
  42932. return this.easeInCore(gradient);
  42933. case EasingFunction.EASINGMODE_EASEOUT:
  42934. return (1 - this.easeInCore(1 - gradient));
  42935. }
  42936. if (gradient >= 0.5) {
  42937. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42938. }
  42939. return (this.easeInCore(gradient * 2) * 0.5);
  42940. };
  42941. //Statics
  42942. EasingFunction._EASINGMODE_EASEIN = 0;
  42943. EasingFunction._EASINGMODE_EASEOUT = 1;
  42944. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42945. return EasingFunction;
  42946. }());
  42947. BABYLON.EasingFunction = EasingFunction;
  42948. var CircleEase = /** @class */ (function (_super) {
  42949. __extends(CircleEase, _super);
  42950. function CircleEase() {
  42951. return _super !== null && _super.apply(this, arguments) || this;
  42952. }
  42953. CircleEase.prototype.easeInCore = function (gradient) {
  42954. gradient = Math.max(0, Math.min(1, gradient));
  42955. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42956. };
  42957. return CircleEase;
  42958. }(EasingFunction));
  42959. BABYLON.CircleEase = CircleEase;
  42960. var BackEase = /** @class */ (function (_super) {
  42961. __extends(BackEase, _super);
  42962. function BackEase(amplitude) {
  42963. if (amplitude === void 0) { amplitude = 1; }
  42964. var _this = _super.call(this) || this;
  42965. _this.amplitude = amplitude;
  42966. return _this;
  42967. }
  42968. BackEase.prototype.easeInCore = function (gradient) {
  42969. var num = Math.max(0, this.amplitude);
  42970. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42971. };
  42972. return BackEase;
  42973. }(EasingFunction));
  42974. BABYLON.BackEase = BackEase;
  42975. var BounceEase = /** @class */ (function (_super) {
  42976. __extends(BounceEase, _super);
  42977. function BounceEase(bounces, bounciness) {
  42978. if (bounces === void 0) { bounces = 3; }
  42979. if (bounciness === void 0) { bounciness = 2; }
  42980. var _this = _super.call(this) || this;
  42981. _this.bounces = bounces;
  42982. _this.bounciness = bounciness;
  42983. return _this;
  42984. }
  42985. BounceEase.prototype.easeInCore = function (gradient) {
  42986. var y = Math.max(0.0, this.bounces);
  42987. var bounciness = this.bounciness;
  42988. if (bounciness <= 1.0) {
  42989. bounciness = 1.001;
  42990. }
  42991. var num9 = Math.pow(bounciness, y);
  42992. var num5 = 1.0 - bounciness;
  42993. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42994. var num15 = gradient * num4;
  42995. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42996. var num3 = Math.floor(num65);
  42997. var num13 = num3 + 1.0;
  42998. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42999. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43000. var num7 = (num8 + num12) * 0.5;
  43001. var num6 = gradient - num7;
  43002. var num2 = num7 - num8;
  43003. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43004. };
  43005. return BounceEase;
  43006. }(EasingFunction));
  43007. BABYLON.BounceEase = BounceEase;
  43008. var CubicEase = /** @class */ (function (_super) {
  43009. __extends(CubicEase, _super);
  43010. function CubicEase() {
  43011. return _super !== null && _super.apply(this, arguments) || this;
  43012. }
  43013. CubicEase.prototype.easeInCore = function (gradient) {
  43014. return (gradient * gradient * gradient);
  43015. };
  43016. return CubicEase;
  43017. }(EasingFunction));
  43018. BABYLON.CubicEase = CubicEase;
  43019. var ElasticEase = /** @class */ (function (_super) {
  43020. __extends(ElasticEase, _super);
  43021. function ElasticEase(oscillations, springiness) {
  43022. if (oscillations === void 0) { oscillations = 3; }
  43023. if (springiness === void 0) { springiness = 3; }
  43024. var _this = _super.call(this) || this;
  43025. _this.oscillations = oscillations;
  43026. _this.springiness = springiness;
  43027. return _this;
  43028. }
  43029. ElasticEase.prototype.easeInCore = function (gradient) {
  43030. var num2;
  43031. var num3 = Math.max(0.0, this.oscillations);
  43032. var num = Math.max(0.0, this.springiness);
  43033. if (num == 0) {
  43034. num2 = gradient;
  43035. }
  43036. else {
  43037. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43038. }
  43039. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43040. };
  43041. return ElasticEase;
  43042. }(EasingFunction));
  43043. BABYLON.ElasticEase = ElasticEase;
  43044. var ExponentialEase = /** @class */ (function (_super) {
  43045. __extends(ExponentialEase, _super);
  43046. function ExponentialEase(exponent) {
  43047. if (exponent === void 0) { exponent = 2; }
  43048. var _this = _super.call(this) || this;
  43049. _this.exponent = exponent;
  43050. return _this;
  43051. }
  43052. ExponentialEase.prototype.easeInCore = function (gradient) {
  43053. if (this.exponent <= 0) {
  43054. return gradient;
  43055. }
  43056. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43057. };
  43058. return ExponentialEase;
  43059. }(EasingFunction));
  43060. BABYLON.ExponentialEase = ExponentialEase;
  43061. var PowerEase = /** @class */ (function (_super) {
  43062. __extends(PowerEase, _super);
  43063. function PowerEase(power) {
  43064. if (power === void 0) { power = 2; }
  43065. var _this = _super.call(this) || this;
  43066. _this.power = power;
  43067. return _this;
  43068. }
  43069. PowerEase.prototype.easeInCore = function (gradient) {
  43070. var y = Math.max(0.0, this.power);
  43071. return Math.pow(gradient, y);
  43072. };
  43073. return PowerEase;
  43074. }(EasingFunction));
  43075. BABYLON.PowerEase = PowerEase;
  43076. var QuadraticEase = /** @class */ (function (_super) {
  43077. __extends(QuadraticEase, _super);
  43078. function QuadraticEase() {
  43079. return _super !== null && _super.apply(this, arguments) || this;
  43080. }
  43081. QuadraticEase.prototype.easeInCore = function (gradient) {
  43082. return (gradient * gradient);
  43083. };
  43084. return QuadraticEase;
  43085. }(EasingFunction));
  43086. BABYLON.QuadraticEase = QuadraticEase;
  43087. var QuarticEase = /** @class */ (function (_super) {
  43088. __extends(QuarticEase, _super);
  43089. function QuarticEase() {
  43090. return _super !== null && _super.apply(this, arguments) || this;
  43091. }
  43092. QuarticEase.prototype.easeInCore = function (gradient) {
  43093. return (gradient * gradient * gradient * gradient);
  43094. };
  43095. return QuarticEase;
  43096. }(EasingFunction));
  43097. BABYLON.QuarticEase = QuarticEase;
  43098. var QuinticEase = /** @class */ (function (_super) {
  43099. __extends(QuinticEase, _super);
  43100. function QuinticEase() {
  43101. return _super !== null && _super.apply(this, arguments) || this;
  43102. }
  43103. QuinticEase.prototype.easeInCore = function (gradient) {
  43104. return (gradient * gradient * gradient * gradient * gradient);
  43105. };
  43106. return QuinticEase;
  43107. }(EasingFunction));
  43108. BABYLON.QuinticEase = QuinticEase;
  43109. var SineEase = /** @class */ (function (_super) {
  43110. __extends(SineEase, _super);
  43111. function SineEase() {
  43112. return _super !== null && _super.apply(this, arguments) || this;
  43113. }
  43114. SineEase.prototype.easeInCore = function (gradient) {
  43115. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43116. };
  43117. return SineEase;
  43118. }(EasingFunction));
  43119. BABYLON.SineEase = SineEase;
  43120. var BezierCurveEase = /** @class */ (function (_super) {
  43121. __extends(BezierCurveEase, _super);
  43122. function BezierCurveEase(x1, y1, x2, y2) {
  43123. if (x1 === void 0) { x1 = 0; }
  43124. if (y1 === void 0) { y1 = 0; }
  43125. if (x2 === void 0) { x2 = 1; }
  43126. if (y2 === void 0) { y2 = 1; }
  43127. var _this = _super.call(this) || this;
  43128. _this.x1 = x1;
  43129. _this.y1 = y1;
  43130. _this.x2 = x2;
  43131. _this.y2 = y2;
  43132. return _this;
  43133. }
  43134. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43135. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43136. };
  43137. return BezierCurveEase;
  43138. }(EasingFunction));
  43139. BABYLON.BezierCurveEase = BezierCurveEase;
  43140. })(BABYLON || (BABYLON = {}));
  43141. //# sourceMappingURL=babylon.easing.js.map
  43142. var BABYLON;
  43143. (function (BABYLON) {
  43144. var Condition = /** @class */ (function () {
  43145. function Condition(actionManager) {
  43146. this._actionManager = actionManager;
  43147. }
  43148. Condition.prototype.isValid = function () {
  43149. return true;
  43150. };
  43151. Condition.prototype._getProperty = function (propertyPath) {
  43152. return this._actionManager._getProperty(propertyPath);
  43153. };
  43154. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43155. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43156. };
  43157. Condition.prototype.serialize = function () {
  43158. };
  43159. Condition.prototype._serialize = function (serializedCondition) {
  43160. return {
  43161. type: 2,
  43162. children: [],
  43163. name: serializedCondition.name,
  43164. properties: serializedCondition.properties
  43165. };
  43166. };
  43167. return Condition;
  43168. }());
  43169. BABYLON.Condition = Condition;
  43170. var ValueCondition = /** @class */ (function (_super) {
  43171. __extends(ValueCondition, _super);
  43172. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43173. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43174. var _this = _super.call(this, actionManager) || this;
  43175. _this.propertyPath = propertyPath;
  43176. _this.value = value;
  43177. _this.operator = operator;
  43178. _this._target = target;
  43179. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43180. _this._property = _this._getProperty(_this.propertyPath);
  43181. return _this;
  43182. }
  43183. Object.defineProperty(ValueCondition, "IsEqual", {
  43184. get: function () {
  43185. return ValueCondition._IsEqual;
  43186. },
  43187. enumerable: true,
  43188. configurable: true
  43189. });
  43190. Object.defineProperty(ValueCondition, "IsDifferent", {
  43191. get: function () {
  43192. return ValueCondition._IsDifferent;
  43193. },
  43194. enumerable: true,
  43195. configurable: true
  43196. });
  43197. Object.defineProperty(ValueCondition, "IsGreater", {
  43198. get: function () {
  43199. return ValueCondition._IsGreater;
  43200. },
  43201. enumerable: true,
  43202. configurable: true
  43203. });
  43204. Object.defineProperty(ValueCondition, "IsLesser", {
  43205. get: function () {
  43206. return ValueCondition._IsLesser;
  43207. },
  43208. enumerable: true,
  43209. configurable: true
  43210. });
  43211. // Methods
  43212. ValueCondition.prototype.isValid = function () {
  43213. switch (this.operator) {
  43214. case ValueCondition.IsGreater:
  43215. return this._effectiveTarget[this._property] > this.value;
  43216. case ValueCondition.IsLesser:
  43217. return this._effectiveTarget[this._property] < this.value;
  43218. case ValueCondition.IsEqual:
  43219. case ValueCondition.IsDifferent:
  43220. var check;
  43221. if (this.value.equals) {
  43222. check = this.value.equals(this._effectiveTarget[this._property]);
  43223. }
  43224. else {
  43225. check = this.value === this._effectiveTarget[this._property];
  43226. }
  43227. return this.operator === ValueCondition.IsEqual ? check : !check;
  43228. }
  43229. return false;
  43230. };
  43231. ValueCondition.prototype.serialize = function () {
  43232. return this._serialize({
  43233. name: "ValueCondition",
  43234. properties: [
  43235. BABYLON.Action._GetTargetProperty(this._target),
  43236. { name: "propertyPath", value: this.propertyPath },
  43237. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43238. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43239. ]
  43240. });
  43241. };
  43242. ValueCondition.GetOperatorName = function (operator) {
  43243. switch (operator) {
  43244. case ValueCondition._IsEqual: return "IsEqual";
  43245. case ValueCondition._IsDifferent: return "IsDifferent";
  43246. case ValueCondition._IsGreater: return "IsGreater";
  43247. case ValueCondition._IsLesser: return "IsLesser";
  43248. default: return "";
  43249. }
  43250. };
  43251. // Statics
  43252. ValueCondition._IsEqual = 0;
  43253. ValueCondition._IsDifferent = 1;
  43254. ValueCondition._IsGreater = 2;
  43255. ValueCondition._IsLesser = 3;
  43256. return ValueCondition;
  43257. }(Condition));
  43258. BABYLON.ValueCondition = ValueCondition;
  43259. var PredicateCondition = /** @class */ (function (_super) {
  43260. __extends(PredicateCondition, _super);
  43261. function PredicateCondition(actionManager, predicate) {
  43262. var _this = _super.call(this, actionManager) || this;
  43263. _this.predicate = predicate;
  43264. return _this;
  43265. }
  43266. PredicateCondition.prototype.isValid = function () {
  43267. return this.predicate();
  43268. };
  43269. return PredicateCondition;
  43270. }(Condition));
  43271. BABYLON.PredicateCondition = PredicateCondition;
  43272. var StateCondition = /** @class */ (function (_super) {
  43273. __extends(StateCondition, _super);
  43274. function StateCondition(actionManager, target, value) {
  43275. var _this = _super.call(this, actionManager) || this;
  43276. _this.value = value;
  43277. _this._target = target;
  43278. return _this;
  43279. }
  43280. // Methods
  43281. StateCondition.prototype.isValid = function () {
  43282. return this._target.state === this.value;
  43283. };
  43284. StateCondition.prototype.serialize = function () {
  43285. return this._serialize({
  43286. name: "StateCondition",
  43287. properties: [
  43288. BABYLON.Action._GetTargetProperty(this._target),
  43289. { name: "value", value: this.value }
  43290. ]
  43291. });
  43292. };
  43293. return StateCondition;
  43294. }(Condition));
  43295. BABYLON.StateCondition = StateCondition;
  43296. })(BABYLON || (BABYLON = {}));
  43297. //# sourceMappingURL=babylon.condition.js.map
  43298. var BABYLON;
  43299. (function (BABYLON) {
  43300. var Action = /** @class */ (function () {
  43301. function Action(triggerOptions, condition) {
  43302. this.triggerOptions = triggerOptions;
  43303. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43304. if (triggerOptions.parameter) {
  43305. this.trigger = triggerOptions.trigger;
  43306. this._triggerParameter = triggerOptions.parameter;
  43307. }
  43308. else {
  43309. this.trigger = triggerOptions;
  43310. }
  43311. this._nextActiveAction = this;
  43312. this._condition = condition;
  43313. }
  43314. // Methods
  43315. Action.prototype._prepare = function () {
  43316. };
  43317. Action.prototype.getTriggerParameter = function () {
  43318. return this._triggerParameter;
  43319. };
  43320. Action.prototype._executeCurrent = function (evt) {
  43321. if (this._nextActiveAction._condition) {
  43322. var condition = this._nextActiveAction._condition;
  43323. var currentRenderId = this._actionManager.getScene().getRenderId();
  43324. // We cache the current evaluation for the current frame
  43325. if (condition._evaluationId === currentRenderId) {
  43326. if (!condition._currentResult) {
  43327. return;
  43328. }
  43329. }
  43330. else {
  43331. condition._evaluationId = currentRenderId;
  43332. if (!condition.isValid()) {
  43333. condition._currentResult = false;
  43334. return;
  43335. }
  43336. condition._currentResult = true;
  43337. }
  43338. }
  43339. this.onBeforeExecuteObservable.notifyObservers(this);
  43340. this._nextActiveAction.execute(evt);
  43341. this.skipToNextActiveAction();
  43342. };
  43343. Action.prototype.execute = function (evt) {
  43344. };
  43345. Action.prototype.skipToNextActiveAction = function () {
  43346. if (this._nextActiveAction._child) {
  43347. if (!this._nextActiveAction._child._actionManager) {
  43348. this._nextActiveAction._child._actionManager = this._actionManager;
  43349. }
  43350. this._nextActiveAction = this._nextActiveAction._child;
  43351. }
  43352. else {
  43353. this._nextActiveAction = this;
  43354. }
  43355. };
  43356. Action.prototype.then = function (action) {
  43357. this._child = action;
  43358. action._actionManager = this._actionManager;
  43359. action._prepare();
  43360. return action;
  43361. };
  43362. Action.prototype._getProperty = function (propertyPath) {
  43363. return this._actionManager._getProperty(propertyPath);
  43364. };
  43365. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43366. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43367. };
  43368. Action.prototype.serialize = function (parent) {
  43369. };
  43370. // Called by BABYLON.Action objects in serialize(...). Internal use
  43371. Action.prototype._serialize = function (serializedAction, parent) {
  43372. var serializationObject = {
  43373. type: 1,
  43374. children: [],
  43375. name: serializedAction.name,
  43376. properties: serializedAction.properties || []
  43377. };
  43378. // Serialize child
  43379. if (this._child) {
  43380. this._child.serialize(serializationObject);
  43381. }
  43382. // Check if "this" has a condition
  43383. if (this._condition) {
  43384. var serializedCondition = this._condition.serialize();
  43385. serializedCondition.children.push(serializationObject);
  43386. if (parent) {
  43387. parent.children.push(serializedCondition);
  43388. }
  43389. return serializedCondition;
  43390. }
  43391. if (parent) {
  43392. parent.children.push(serializationObject);
  43393. }
  43394. return serializationObject;
  43395. };
  43396. Action._SerializeValueAsString = function (value) {
  43397. if (typeof value === "number") {
  43398. return value.toString();
  43399. }
  43400. if (typeof value === "boolean") {
  43401. return value ? "true" : "false";
  43402. }
  43403. if (value instanceof BABYLON.Vector2) {
  43404. return value.x + ", " + value.y;
  43405. }
  43406. if (value instanceof BABYLON.Vector3) {
  43407. return value.x + ", " + value.y + ", " + value.z;
  43408. }
  43409. if (value instanceof BABYLON.Color3) {
  43410. return value.r + ", " + value.g + ", " + value.b;
  43411. }
  43412. if (value instanceof BABYLON.Color4) {
  43413. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43414. }
  43415. return value; // string
  43416. };
  43417. Action._GetTargetProperty = function (target) {
  43418. return {
  43419. name: "target",
  43420. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43421. : target instanceof BABYLON.Light ? "LightProperties"
  43422. : target instanceof BABYLON.Camera ? "CameraProperties"
  43423. : "SceneProperties",
  43424. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43425. };
  43426. };
  43427. return Action;
  43428. }());
  43429. BABYLON.Action = Action;
  43430. })(BABYLON || (BABYLON = {}));
  43431. //# sourceMappingURL=babylon.action.js.map
  43432. var BABYLON;
  43433. (function (BABYLON) {
  43434. /**
  43435. * ActionEvent is the event beint sent when an action is triggered.
  43436. */
  43437. var ActionEvent = /** @class */ (function () {
  43438. /**
  43439. * @param source The mesh or sprite that triggered the action.
  43440. * @param pointerX The X mouse cursor position at the time of the event
  43441. * @param pointerY The Y mouse cursor position at the time of the event
  43442. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43443. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43444. */
  43445. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43446. this.source = source;
  43447. this.pointerX = pointerX;
  43448. this.pointerY = pointerY;
  43449. this.meshUnderPointer = meshUnderPointer;
  43450. this.sourceEvent = sourceEvent;
  43451. this.additionalData = additionalData;
  43452. }
  43453. /**
  43454. * Helper function to auto-create an ActionEvent from a source mesh.
  43455. * @param source The source mesh that triggered the event
  43456. * @param evt {Event} The original (browser) event
  43457. */
  43458. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43459. var scene = source.getScene();
  43460. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43461. };
  43462. /**
  43463. * Helper function to auto-create an ActionEvent from a source mesh.
  43464. * @param source The source sprite that triggered the event
  43465. * @param scene Scene associated with the sprite
  43466. * @param evt {Event} The original (browser) event
  43467. */
  43468. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43469. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43470. };
  43471. /**
  43472. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43473. * @param scene the scene where the event occurred
  43474. * @param evt {Event} The original (browser) event
  43475. */
  43476. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43477. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43478. };
  43479. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43480. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43481. };
  43482. return ActionEvent;
  43483. }());
  43484. BABYLON.ActionEvent = ActionEvent;
  43485. /**
  43486. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43487. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43488. */
  43489. var ActionManager = /** @class */ (function () {
  43490. function ActionManager(scene) {
  43491. // Members
  43492. this.actions = new Array();
  43493. this.hoverCursor = '';
  43494. this._scene = scene;
  43495. scene._actionManagers.push(this);
  43496. }
  43497. Object.defineProperty(ActionManager, "NothingTrigger", {
  43498. get: function () {
  43499. return ActionManager._NothingTrigger;
  43500. },
  43501. enumerable: true,
  43502. configurable: true
  43503. });
  43504. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43505. get: function () {
  43506. return ActionManager._OnPickTrigger;
  43507. },
  43508. enumerable: true,
  43509. configurable: true
  43510. });
  43511. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43512. get: function () {
  43513. return ActionManager._OnLeftPickTrigger;
  43514. },
  43515. enumerable: true,
  43516. configurable: true
  43517. });
  43518. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43519. get: function () {
  43520. return ActionManager._OnRightPickTrigger;
  43521. },
  43522. enumerable: true,
  43523. configurable: true
  43524. });
  43525. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43526. get: function () {
  43527. return ActionManager._OnCenterPickTrigger;
  43528. },
  43529. enumerable: true,
  43530. configurable: true
  43531. });
  43532. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43533. get: function () {
  43534. return ActionManager._OnPickDownTrigger;
  43535. },
  43536. enumerable: true,
  43537. configurable: true
  43538. });
  43539. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43540. get: function () {
  43541. return ActionManager._OnDoublePickTrigger;
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43547. get: function () {
  43548. return ActionManager._OnPickUpTrigger;
  43549. },
  43550. enumerable: true,
  43551. configurable: true
  43552. });
  43553. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43554. /// This trigger will only be raised if you also declared a OnPickDown
  43555. get: function () {
  43556. return ActionManager._OnPickOutTrigger;
  43557. },
  43558. enumerable: true,
  43559. configurable: true
  43560. });
  43561. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43562. get: function () {
  43563. return ActionManager._OnLongPressTrigger;
  43564. },
  43565. enumerable: true,
  43566. configurable: true
  43567. });
  43568. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43569. get: function () {
  43570. return ActionManager._OnPointerOverTrigger;
  43571. },
  43572. enumerable: true,
  43573. configurable: true
  43574. });
  43575. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43576. get: function () {
  43577. return ActionManager._OnPointerOutTrigger;
  43578. },
  43579. enumerable: true,
  43580. configurable: true
  43581. });
  43582. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43583. get: function () {
  43584. return ActionManager._OnEveryFrameTrigger;
  43585. },
  43586. enumerable: true,
  43587. configurable: true
  43588. });
  43589. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43590. get: function () {
  43591. return ActionManager._OnIntersectionEnterTrigger;
  43592. },
  43593. enumerable: true,
  43594. configurable: true
  43595. });
  43596. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43597. get: function () {
  43598. return ActionManager._OnIntersectionExitTrigger;
  43599. },
  43600. enumerable: true,
  43601. configurable: true
  43602. });
  43603. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43604. get: function () {
  43605. return ActionManager._OnKeyDownTrigger;
  43606. },
  43607. enumerable: true,
  43608. configurable: true
  43609. });
  43610. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43611. get: function () {
  43612. return ActionManager._OnKeyUpTrigger;
  43613. },
  43614. enumerable: true,
  43615. configurable: true
  43616. });
  43617. // Methods
  43618. ActionManager.prototype.dispose = function () {
  43619. var index = this._scene._actionManagers.indexOf(this);
  43620. for (var i = 0; i < this.actions.length; i++) {
  43621. var action = this.actions[i];
  43622. ActionManager.Triggers[action.trigger]--;
  43623. if (ActionManager.Triggers[action.trigger] === 0) {
  43624. delete ActionManager.Triggers[action.trigger];
  43625. }
  43626. }
  43627. if (index > -1) {
  43628. this._scene._actionManagers.splice(index, 1);
  43629. }
  43630. };
  43631. ActionManager.prototype.getScene = function () {
  43632. return this._scene;
  43633. };
  43634. /**
  43635. * Does this action manager handles actions of any of the given triggers
  43636. * @param {number[]} triggers - the triggers to be tested
  43637. * @return {boolean} whether one (or more) of the triggers is handeled
  43638. */
  43639. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43640. for (var index = 0; index < this.actions.length; index++) {
  43641. var action = this.actions[index];
  43642. if (triggers.indexOf(action.trigger) > -1) {
  43643. return true;
  43644. }
  43645. }
  43646. return false;
  43647. };
  43648. /**
  43649. * Does this action manager handles actions of a given trigger
  43650. * @param {number} trigger - the trigger to be tested
  43651. * @return {boolean} whether the trigger is handeled
  43652. */
  43653. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43654. for (var index = 0; index < this.actions.length; index++) {
  43655. var action = this.actions[index];
  43656. if (action.trigger === trigger) {
  43657. return true;
  43658. }
  43659. }
  43660. return false;
  43661. };
  43662. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43663. /**
  43664. * Does this action manager has pointer triggers
  43665. * @return {boolean} whether or not it has pointer triggers
  43666. */
  43667. get: function () {
  43668. for (var index = 0; index < this.actions.length; index++) {
  43669. var action = this.actions[index];
  43670. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43671. return true;
  43672. }
  43673. }
  43674. return false;
  43675. },
  43676. enumerable: true,
  43677. configurable: true
  43678. });
  43679. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43680. /**
  43681. * Does this action manager has pick triggers
  43682. * @return {boolean} whether or not it has pick triggers
  43683. */
  43684. get: function () {
  43685. for (var index = 0; index < this.actions.length; index++) {
  43686. var action = this.actions[index];
  43687. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43688. return true;
  43689. }
  43690. }
  43691. return false;
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. Object.defineProperty(ActionManager, "HasTriggers", {
  43697. /**
  43698. * Does exist one action manager with at least one trigger
  43699. * @return {boolean} whether or not it exists one action manager with one trigger
  43700. **/
  43701. get: function () {
  43702. for (var t in ActionManager.Triggers) {
  43703. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43704. return true;
  43705. }
  43706. }
  43707. return false;
  43708. },
  43709. enumerable: true,
  43710. configurable: true
  43711. });
  43712. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43713. /**
  43714. * Does exist one action manager with at least one pick trigger
  43715. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43716. **/
  43717. get: function () {
  43718. for (var t in ActionManager.Triggers) {
  43719. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43720. var t_int = parseInt(t);
  43721. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43722. return true;
  43723. }
  43724. }
  43725. }
  43726. return false;
  43727. },
  43728. enumerable: true,
  43729. configurable: true
  43730. });
  43731. /**
  43732. * Does exist one action manager that handles actions of a given trigger
  43733. * @param {number} trigger - the trigger to be tested
  43734. * @return {boolean} whether the trigger is handeled by at least one action manager
  43735. **/
  43736. ActionManager.HasSpecificTrigger = function (trigger) {
  43737. for (var t in ActionManager.Triggers) {
  43738. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43739. var t_int = parseInt(t);
  43740. if (t_int === trigger) {
  43741. return true;
  43742. }
  43743. }
  43744. }
  43745. return false;
  43746. };
  43747. /**
  43748. * Registers an action to this action manager
  43749. * @param {BABYLON.Action} action - the action to be registered
  43750. * @return {BABYLON.Action} the action amended (prepared) after registration
  43751. */
  43752. ActionManager.prototype.registerAction = function (action) {
  43753. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43754. if (this.getScene().actionManager !== this) {
  43755. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43756. return null;
  43757. }
  43758. }
  43759. this.actions.push(action);
  43760. if (ActionManager.Triggers[action.trigger]) {
  43761. ActionManager.Triggers[action.trigger]++;
  43762. }
  43763. else {
  43764. ActionManager.Triggers[action.trigger] = 1;
  43765. }
  43766. action._actionManager = this;
  43767. action._prepare();
  43768. return action;
  43769. };
  43770. /**
  43771. * Process a specific trigger
  43772. * @param {number} trigger - the trigger to process
  43773. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43774. */
  43775. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43776. for (var index = 0; index < this.actions.length; index++) {
  43777. var action = this.actions[index];
  43778. if (action.trigger === trigger) {
  43779. if (evt) {
  43780. if (trigger === ActionManager.OnKeyUpTrigger
  43781. || trigger === ActionManager.OnKeyDownTrigger) {
  43782. var parameter = action.getTriggerParameter();
  43783. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43784. if (!parameter.toLowerCase) {
  43785. continue;
  43786. }
  43787. var lowerCase = parameter.toLowerCase();
  43788. if (lowerCase !== evt.sourceEvent.key) {
  43789. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43790. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43791. if (actualkey !== lowerCase) {
  43792. continue;
  43793. }
  43794. }
  43795. }
  43796. }
  43797. }
  43798. action._executeCurrent(evt);
  43799. }
  43800. }
  43801. };
  43802. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43803. var properties = propertyPath.split(".");
  43804. for (var index = 0; index < properties.length - 1; index++) {
  43805. target = target[properties[index]];
  43806. }
  43807. return target;
  43808. };
  43809. ActionManager.prototype._getProperty = function (propertyPath) {
  43810. var properties = propertyPath.split(".");
  43811. return properties[properties.length - 1];
  43812. };
  43813. ActionManager.prototype.serialize = function (name) {
  43814. var root = {
  43815. children: new Array(),
  43816. name: name,
  43817. type: 3,
  43818. properties: new Array() // Empty for root but required
  43819. };
  43820. for (var i = 0; i < this.actions.length; i++) {
  43821. var triggerObject = {
  43822. type: 0,
  43823. children: new Array(),
  43824. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43825. properties: new Array()
  43826. };
  43827. var triggerOptions = this.actions[i].triggerOptions;
  43828. if (triggerOptions && typeof triggerOptions !== "number") {
  43829. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43830. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43831. }
  43832. else {
  43833. var parameter = {};
  43834. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43835. if (triggerOptions.parameter.mesh) {
  43836. parameter._meshId = triggerOptions.parameter.mesh.id;
  43837. }
  43838. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43839. }
  43840. }
  43841. // Serialize child action, recursively
  43842. this.actions[i].serialize(triggerObject);
  43843. // Add serialized trigger
  43844. root.children.push(triggerObject);
  43845. }
  43846. return root;
  43847. };
  43848. ActionManager.Parse = function (parsedActions, object, scene) {
  43849. var actionManager = new ActionManager(scene);
  43850. if (object === null)
  43851. scene.actionManager = actionManager;
  43852. else
  43853. object.actionManager = actionManager;
  43854. // instanciate a new object
  43855. var instanciate = function (name, params) {
  43856. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  43857. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43858. newInstance.constructor.apply(newInstance, params);
  43859. return newInstance;
  43860. };
  43861. var parseParameter = function (name, value, target, propertyPath) {
  43862. if (propertyPath === null) {
  43863. // String, boolean or float
  43864. var floatValue = parseFloat(value);
  43865. if (value === "true" || value === "false")
  43866. return value === "true";
  43867. else
  43868. return isNaN(floatValue) ? value : floatValue;
  43869. }
  43870. var effectiveTarget = propertyPath.split(".");
  43871. var values = value.split(",");
  43872. // Get effective Target
  43873. for (var i = 0; i < effectiveTarget.length; i++) {
  43874. target = target[effectiveTarget[i]];
  43875. }
  43876. // Return appropriate value with its type
  43877. if (typeof (target) === "boolean")
  43878. return values[0] === "true";
  43879. if (typeof (target) === "string")
  43880. return values[0];
  43881. // Parameters with multiple values such as Vector3 etc.
  43882. var split = new Array();
  43883. for (var i = 0; i < values.length; i++)
  43884. split.push(parseFloat(values[i]));
  43885. if (target instanceof BABYLON.Vector3)
  43886. return BABYLON.Vector3.FromArray(split);
  43887. if (target instanceof BABYLON.Vector4)
  43888. return BABYLON.Vector4.FromArray(split);
  43889. if (target instanceof BABYLON.Color3)
  43890. return BABYLON.Color3.FromArray(split);
  43891. if (target instanceof BABYLON.Color4)
  43892. return BABYLON.Color4.FromArray(split);
  43893. return parseFloat(values[0]);
  43894. };
  43895. // traverse graph per trigger
  43896. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43897. if (combineArray === void 0) { combineArray = null; }
  43898. if (parsedAction.detached)
  43899. return;
  43900. var parameters = new Array();
  43901. var target = null;
  43902. var propertyPath = null;
  43903. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43904. // Parameters
  43905. if (parsedAction.type === 2)
  43906. parameters.push(actionManager);
  43907. else
  43908. parameters.push(trigger);
  43909. if (combine) {
  43910. var actions = new Array();
  43911. for (var j = 0; j < parsedAction.combine.length; j++) {
  43912. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43913. }
  43914. parameters.push(actions);
  43915. }
  43916. else {
  43917. for (var i = 0; i < parsedAction.properties.length; i++) {
  43918. var value = parsedAction.properties[i].value;
  43919. var name = parsedAction.properties[i].name;
  43920. var targetType = parsedAction.properties[i].targetType;
  43921. if (name === "target")
  43922. if (targetType !== null && targetType === "SceneProperties")
  43923. value = target = scene;
  43924. else
  43925. value = target = scene.getNodeByName(value);
  43926. else if (name === "parent")
  43927. value = scene.getNodeByName(value);
  43928. else if (name === "sound")
  43929. value = scene.getSoundByName(value);
  43930. else if (name !== "propertyPath") {
  43931. if (parsedAction.type === 2 && name === "operator")
  43932. value = BABYLON.ValueCondition[value];
  43933. else
  43934. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43935. }
  43936. else {
  43937. propertyPath = value;
  43938. }
  43939. parameters.push(value);
  43940. }
  43941. }
  43942. if (combineArray === null) {
  43943. parameters.push(condition);
  43944. }
  43945. else {
  43946. parameters.push(null);
  43947. }
  43948. // If interpolate value action
  43949. if (parsedAction.name === "InterpolateValueAction") {
  43950. var param = parameters[parameters.length - 2];
  43951. parameters[parameters.length - 1] = param;
  43952. parameters[parameters.length - 2] = condition;
  43953. }
  43954. // Action or condition(s) and not CombineAction
  43955. var newAction = instanciate(parsedAction.name, parameters);
  43956. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43957. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43958. if (action)
  43959. action.then(nothing);
  43960. else
  43961. actionManager.registerAction(nothing);
  43962. action = nothing;
  43963. }
  43964. if (combineArray === null) {
  43965. if (newAction instanceof BABYLON.Condition) {
  43966. condition = newAction;
  43967. newAction = action;
  43968. }
  43969. else {
  43970. condition = null;
  43971. if (action)
  43972. action.then(newAction);
  43973. else
  43974. actionManager.registerAction(newAction);
  43975. }
  43976. }
  43977. else {
  43978. combineArray.push(newAction);
  43979. }
  43980. for (var i = 0; i < parsedAction.children.length; i++)
  43981. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43982. };
  43983. // triggers
  43984. for (var i = 0; i < parsedActions.children.length; i++) {
  43985. var triggerParams;
  43986. var trigger = parsedActions.children[i];
  43987. if (trigger.properties.length > 0) {
  43988. var param = trigger.properties[0].value;
  43989. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43990. if (value._meshId) {
  43991. value.mesh = scene.getMeshByID(value._meshId);
  43992. }
  43993. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43994. }
  43995. else
  43996. triggerParams = ActionManager[trigger.name];
  43997. for (var j = 0; j < trigger.children.length; j++) {
  43998. if (!trigger.detached)
  43999. traverse(trigger.children[j], triggerParams, null, null);
  44000. }
  44001. }
  44002. };
  44003. ActionManager.GetTriggerName = function (trigger) {
  44004. switch (trigger) {
  44005. case 0: return "NothingTrigger";
  44006. case 1: return "OnPickTrigger";
  44007. case 2: return "OnLeftPickTrigger";
  44008. case 3: return "OnRightPickTrigger";
  44009. case 4: return "OnCenterPickTrigger";
  44010. case 5: return "OnPickDownTrigger";
  44011. case 6: return "OnPickUpTrigger";
  44012. case 7: return "OnLongPressTrigger";
  44013. case 8: return "OnPointerOverTrigger";
  44014. case 9: return "OnPointerOutTrigger";
  44015. case 10: return "OnEveryFrameTrigger";
  44016. case 11: return "OnIntersectionEnterTrigger";
  44017. case 12: return "OnIntersectionExitTrigger";
  44018. case 13: return "OnKeyDownTrigger";
  44019. case 14: return "OnKeyUpTrigger";
  44020. case 15: return "OnPickOutTrigger";
  44021. default: return "";
  44022. }
  44023. };
  44024. // Statics
  44025. ActionManager._NothingTrigger = 0;
  44026. ActionManager._OnPickTrigger = 1;
  44027. ActionManager._OnLeftPickTrigger = 2;
  44028. ActionManager._OnRightPickTrigger = 3;
  44029. ActionManager._OnCenterPickTrigger = 4;
  44030. ActionManager._OnPickDownTrigger = 5;
  44031. ActionManager._OnDoublePickTrigger = 6;
  44032. ActionManager._OnPickUpTrigger = 7;
  44033. ActionManager._OnLongPressTrigger = 8;
  44034. ActionManager._OnPointerOverTrigger = 9;
  44035. ActionManager._OnPointerOutTrigger = 10;
  44036. ActionManager._OnEveryFrameTrigger = 11;
  44037. ActionManager._OnIntersectionEnterTrigger = 12;
  44038. ActionManager._OnIntersectionExitTrigger = 13;
  44039. ActionManager._OnKeyDownTrigger = 14;
  44040. ActionManager._OnKeyUpTrigger = 15;
  44041. ActionManager._OnPickOutTrigger = 16;
  44042. ActionManager.Triggers = {};
  44043. return ActionManager;
  44044. }());
  44045. BABYLON.ActionManager = ActionManager;
  44046. })(BABYLON || (BABYLON = {}));
  44047. //# sourceMappingURL=babylon.actionManager.js.map
  44048. var BABYLON;
  44049. (function (BABYLON) {
  44050. var InterpolateValueAction = /** @class */ (function (_super) {
  44051. __extends(InterpolateValueAction, _super);
  44052. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44053. if (duration === void 0) { duration = 1000; }
  44054. var _this = _super.call(this, triggerOptions, condition) || this;
  44055. _this.propertyPath = propertyPath;
  44056. _this.value = value;
  44057. _this.duration = duration;
  44058. _this.stopOtherAnimations = stopOtherAnimations;
  44059. _this.onInterpolationDone = onInterpolationDone;
  44060. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44061. _this._target = _this._effectiveTarget = target;
  44062. return _this;
  44063. }
  44064. InterpolateValueAction.prototype._prepare = function () {
  44065. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44066. this._property = this._getProperty(this.propertyPath);
  44067. };
  44068. InterpolateValueAction.prototype.execute = function () {
  44069. var _this = this;
  44070. var scene = this._actionManager.getScene();
  44071. var keys = [
  44072. {
  44073. frame: 0,
  44074. value: this._effectiveTarget[this._property]
  44075. }, {
  44076. frame: 100,
  44077. value: this.value
  44078. }
  44079. ];
  44080. var dataType;
  44081. if (typeof this.value === "number") {
  44082. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44083. }
  44084. else if (this.value instanceof BABYLON.Color3) {
  44085. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44086. }
  44087. else if (this.value instanceof BABYLON.Vector3) {
  44088. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44089. }
  44090. else if (this.value instanceof BABYLON.Matrix) {
  44091. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44092. }
  44093. else if (this.value instanceof BABYLON.Quaternion) {
  44094. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44095. }
  44096. else {
  44097. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44098. return;
  44099. }
  44100. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44101. animation.setKeys(keys);
  44102. if (this.stopOtherAnimations) {
  44103. scene.stopAnimation(this._effectiveTarget);
  44104. }
  44105. var wrapper = function () {
  44106. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44107. if (_this.onInterpolationDone) {
  44108. _this.onInterpolationDone();
  44109. }
  44110. };
  44111. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44112. };
  44113. InterpolateValueAction.prototype.serialize = function (parent) {
  44114. return _super.prototype._serialize.call(this, {
  44115. name: "InterpolateValueAction",
  44116. properties: [
  44117. BABYLON.Action._GetTargetProperty(this._target),
  44118. { name: "propertyPath", value: this.propertyPath },
  44119. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44120. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44121. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44122. ]
  44123. }, parent);
  44124. };
  44125. return InterpolateValueAction;
  44126. }(BABYLON.Action));
  44127. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44128. })(BABYLON || (BABYLON = {}));
  44129. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44130. var BABYLON;
  44131. (function (BABYLON) {
  44132. var SwitchBooleanAction = /** @class */ (function (_super) {
  44133. __extends(SwitchBooleanAction, _super);
  44134. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44135. var _this = _super.call(this, triggerOptions, condition) || this;
  44136. _this.propertyPath = propertyPath;
  44137. _this._target = _this._effectiveTarget = target;
  44138. return _this;
  44139. }
  44140. SwitchBooleanAction.prototype._prepare = function () {
  44141. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44142. this._property = this._getProperty(this.propertyPath);
  44143. };
  44144. SwitchBooleanAction.prototype.execute = function () {
  44145. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44146. };
  44147. SwitchBooleanAction.prototype.serialize = function (parent) {
  44148. return _super.prototype._serialize.call(this, {
  44149. name: "SwitchBooleanAction",
  44150. properties: [
  44151. BABYLON.Action._GetTargetProperty(this._target),
  44152. { name: "propertyPath", value: this.propertyPath }
  44153. ]
  44154. }, parent);
  44155. };
  44156. return SwitchBooleanAction;
  44157. }(BABYLON.Action));
  44158. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44159. var SetStateAction = /** @class */ (function (_super) {
  44160. __extends(SetStateAction, _super);
  44161. function SetStateAction(triggerOptions, target, value, condition) {
  44162. var _this = _super.call(this, triggerOptions, condition) || this;
  44163. _this.value = value;
  44164. _this._target = target;
  44165. return _this;
  44166. }
  44167. SetStateAction.prototype.execute = function () {
  44168. this._target.state = this.value;
  44169. };
  44170. SetStateAction.prototype.serialize = function (parent) {
  44171. return _super.prototype._serialize.call(this, {
  44172. name: "SetStateAction",
  44173. properties: [
  44174. BABYLON.Action._GetTargetProperty(this._target),
  44175. { name: "value", value: this.value }
  44176. ]
  44177. }, parent);
  44178. };
  44179. return SetStateAction;
  44180. }(BABYLON.Action));
  44181. BABYLON.SetStateAction = SetStateAction;
  44182. var SetValueAction = /** @class */ (function (_super) {
  44183. __extends(SetValueAction, _super);
  44184. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44185. var _this = _super.call(this, triggerOptions, condition) || this;
  44186. _this.propertyPath = propertyPath;
  44187. _this.value = value;
  44188. _this._target = _this._effectiveTarget = target;
  44189. return _this;
  44190. }
  44191. SetValueAction.prototype._prepare = function () {
  44192. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44193. this._property = this._getProperty(this.propertyPath);
  44194. };
  44195. SetValueAction.prototype.execute = function () {
  44196. this._effectiveTarget[this._property] = this.value;
  44197. if (this._target.markAsDirty) {
  44198. this._target.markAsDirty(this._property);
  44199. }
  44200. };
  44201. SetValueAction.prototype.serialize = function (parent) {
  44202. return _super.prototype._serialize.call(this, {
  44203. name: "SetValueAction",
  44204. properties: [
  44205. BABYLON.Action._GetTargetProperty(this._target),
  44206. { name: "propertyPath", value: this.propertyPath },
  44207. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44208. ]
  44209. }, parent);
  44210. };
  44211. return SetValueAction;
  44212. }(BABYLON.Action));
  44213. BABYLON.SetValueAction = SetValueAction;
  44214. var IncrementValueAction = /** @class */ (function (_super) {
  44215. __extends(IncrementValueAction, _super);
  44216. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44217. var _this = _super.call(this, triggerOptions, condition) || this;
  44218. _this.propertyPath = propertyPath;
  44219. _this.value = value;
  44220. _this._target = _this._effectiveTarget = target;
  44221. return _this;
  44222. }
  44223. IncrementValueAction.prototype._prepare = function () {
  44224. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44225. this._property = this._getProperty(this.propertyPath);
  44226. if (typeof this._effectiveTarget[this._property] !== "number") {
  44227. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44228. }
  44229. };
  44230. IncrementValueAction.prototype.execute = function () {
  44231. this._effectiveTarget[this._property] += this.value;
  44232. if (this._target.markAsDirty) {
  44233. this._target.markAsDirty(this._property);
  44234. }
  44235. };
  44236. IncrementValueAction.prototype.serialize = function (parent) {
  44237. return _super.prototype._serialize.call(this, {
  44238. name: "IncrementValueAction",
  44239. properties: [
  44240. BABYLON.Action._GetTargetProperty(this._target),
  44241. { name: "propertyPath", value: this.propertyPath },
  44242. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44243. ]
  44244. }, parent);
  44245. };
  44246. return IncrementValueAction;
  44247. }(BABYLON.Action));
  44248. BABYLON.IncrementValueAction = IncrementValueAction;
  44249. var PlayAnimationAction = /** @class */ (function (_super) {
  44250. __extends(PlayAnimationAction, _super);
  44251. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44252. var _this = _super.call(this, triggerOptions, condition) || this;
  44253. _this.from = from;
  44254. _this.to = to;
  44255. _this.loop = loop;
  44256. _this._target = target;
  44257. return _this;
  44258. }
  44259. PlayAnimationAction.prototype._prepare = function () {
  44260. };
  44261. PlayAnimationAction.prototype.execute = function () {
  44262. var scene = this._actionManager.getScene();
  44263. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44264. };
  44265. PlayAnimationAction.prototype.serialize = function (parent) {
  44266. return _super.prototype._serialize.call(this, {
  44267. name: "PlayAnimationAction",
  44268. properties: [
  44269. BABYLON.Action._GetTargetProperty(this._target),
  44270. { name: "from", value: String(this.from) },
  44271. { name: "to", value: String(this.to) },
  44272. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44273. ]
  44274. }, parent);
  44275. };
  44276. return PlayAnimationAction;
  44277. }(BABYLON.Action));
  44278. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44279. var StopAnimationAction = /** @class */ (function (_super) {
  44280. __extends(StopAnimationAction, _super);
  44281. function StopAnimationAction(triggerOptions, target, condition) {
  44282. var _this = _super.call(this, triggerOptions, condition) || this;
  44283. _this._target = target;
  44284. return _this;
  44285. }
  44286. StopAnimationAction.prototype._prepare = function () {
  44287. };
  44288. StopAnimationAction.prototype.execute = function () {
  44289. var scene = this._actionManager.getScene();
  44290. scene.stopAnimation(this._target);
  44291. };
  44292. StopAnimationAction.prototype.serialize = function (parent) {
  44293. return _super.prototype._serialize.call(this, {
  44294. name: "StopAnimationAction",
  44295. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44296. }, parent);
  44297. };
  44298. return StopAnimationAction;
  44299. }(BABYLON.Action));
  44300. BABYLON.StopAnimationAction = StopAnimationAction;
  44301. var DoNothingAction = /** @class */ (function (_super) {
  44302. __extends(DoNothingAction, _super);
  44303. function DoNothingAction(triggerOptions, condition) {
  44304. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44305. return _super.call(this, triggerOptions, condition) || this;
  44306. }
  44307. DoNothingAction.prototype.execute = function () {
  44308. };
  44309. DoNothingAction.prototype.serialize = function (parent) {
  44310. return _super.prototype._serialize.call(this, {
  44311. name: "DoNothingAction",
  44312. properties: []
  44313. }, parent);
  44314. };
  44315. return DoNothingAction;
  44316. }(BABYLON.Action));
  44317. BABYLON.DoNothingAction = DoNothingAction;
  44318. var CombineAction = /** @class */ (function (_super) {
  44319. __extends(CombineAction, _super);
  44320. function CombineAction(triggerOptions, children, condition) {
  44321. var _this = _super.call(this, triggerOptions, condition) || this;
  44322. _this.children = children;
  44323. return _this;
  44324. }
  44325. CombineAction.prototype._prepare = function () {
  44326. for (var index = 0; index < this.children.length; index++) {
  44327. this.children[index]._actionManager = this._actionManager;
  44328. this.children[index]._prepare();
  44329. }
  44330. };
  44331. CombineAction.prototype.execute = function (evt) {
  44332. for (var index = 0; index < this.children.length; index++) {
  44333. this.children[index].execute(evt);
  44334. }
  44335. };
  44336. CombineAction.prototype.serialize = function (parent) {
  44337. var serializationObject = _super.prototype._serialize.call(this, {
  44338. name: "CombineAction",
  44339. properties: [],
  44340. combine: []
  44341. }, parent);
  44342. for (var i = 0; i < this.children.length; i++) {
  44343. serializationObject.combine.push(this.children[i].serialize(null));
  44344. }
  44345. return serializationObject;
  44346. };
  44347. return CombineAction;
  44348. }(BABYLON.Action));
  44349. BABYLON.CombineAction = CombineAction;
  44350. var ExecuteCodeAction = /** @class */ (function (_super) {
  44351. __extends(ExecuteCodeAction, _super);
  44352. function ExecuteCodeAction(triggerOptions, func, condition) {
  44353. var _this = _super.call(this, triggerOptions, condition) || this;
  44354. _this.func = func;
  44355. return _this;
  44356. }
  44357. ExecuteCodeAction.prototype.execute = function (evt) {
  44358. this.func(evt);
  44359. };
  44360. return ExecuteCodeAction;
  44361. }(BABYLON.Action));
  44362. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44363. var SetParentAction = /** @class */ (function (_super) {
  44364. __extends(SetParentAction, _super);
  44365. function SetParentAction(triggerOptions, target, parent, condition) {
  44366. var _this = _super.call(this, triggerOptions, condition) || this;
  44367. _this._target = target;
  44368. _this._parent = parent;
  44369. return _this;
  44370. }
  44371. SetParentAction.prototype._prepare = function () {
  44372. };
  44373. SetParentAction.prototype.execute = function () {
  44374. if (this._target.parent === this._parent) {
  44375. return;
  44376. }
  44377. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44378. invertParentWorldMatrix.invert();
  44379. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44380. this._target.parent = this._parent;
  44381. };
  44382. SetParentAction.prototype.serialize = function (parent) {
  44383. return _super.prototype._serialize.call(this, {
  44384. name: "SetParentAction",
  44385. properties: [
  44386. BABYLON.Action._GetTargetProperty(this._target),
  44387. BABYLON.Action._GetTargetProperty(this._parent),
  44388. ]
  44389. }, parent);
  44390. };
  44391. return SetParentAction;
  44392. }(BABYLON.Action));
  44393. BABYLON.SetParentAction = SetParentAction;
  44394. var PlaySoundAction = /** @class */ (function (_super) {
  44395. __extends(PlaySoundAction, _super);
  44396. function PlaySoundAction(triggerOptions, sound, condition) {
  44397. var _this = _super.call(this, triggerOptions, condition) || this;
  44398. _this._sound = sound;
  44399. return _this;
  44400. }
  44401. PlaySoundAction.prototype._prepare = function () {
  44402. };
  44403. PlaySoundAction.prototype.execute = function () {
  44404. if (this._sound !== undefined)
  44405. this._sound.play();
  44406. };
  44407. PlaySoundAction.prototype.serialize = function (parent) {
  44408. return _super.prototype._serialize.call(this, {
  44409. name: "PlaySoundAction",
  44410. properties: [{ name: "sound", value: this._sound.name }]
  44411. }, parent);
  44412. };
  44413. return PlaySoundAction;
  44414. }(BABYLON.Action));
  44415. BABYLON.PlaySoundAction = PlaySoundAction;
  44416. var StopSoundAction = /** @class */ (function (_super) {
  44417. __extends(StopSoundAction, _super);
  44418. function StopSoundAction(triggerOptions, sound, condition) {
  44419. var _this = _super.call(this, triggerOptions, condition) || this;
  44420. _this._sound = sound;
  44421. return _this;
  44422. }
  44423. StopSoundAction.prototype._prepare = function () {
  44424. };
  44425. StopSoundAction.prototype.execute = function () {
  44426. if (this._sound !== undefined)
  44427. this._sound.stop();
  44428. };
  44429. StopSoundAction.prototype.serialize = function (parent) {
  44430. return _super.prototype._serialize.call(this, {
  44431. name: "StopSoundAction",
  44432. properties: [{ name: "sound", value: this._sound.name }]
  44433. }, parent);
  44434. };
  44435. return StopSoundAction;
  44436. }(BABYLON.Action));
  44437. BABYLON.StopSoundAction = StopSoundAction;
  44438. })(BABYLON || (BABYLON = {}));
  44439. //# sourceMappingURL=babylon.directActions.js.map
  44440. var BABYLON;
  44441. (function (BABYLON) {
  44442. var SpriteManager = /** @class */ (function () {
  44443. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44444. if (epsilon === void 0) { epsilon = 0.01; }
  44445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44446. this.name = name;
  44447. this.sprites = new Array();
  44448. this.renderingGroupId = 0;
  44449. this.layerMask = 0x0FFFFFFF;
  44450. this.fogEnabled = true;
  44451. this.isPickable = false;
  44452. /**
  44453. * An event triggered when the manager is disposed.
  44454. * @type {BABYLON.Observable}
  44455. */
  44456. this.onDisposeObservable = new BABYLON.Observable();
  44457. this._vertexBuffers = {};
  44458. this._capacity = capacity;
  44459. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44460. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44461. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44462. if (cellSize.width && cellSize.height) {
  44463. this.cellWidth = cellSize.width;
  44464. this.cellHeight = cellSize.height;
  44465. }
  44466. else if (cellSize !== undefined) {
  44467. this.cellWidth = cellSize;
  44468. this.cellHeight = cellSize;
  44469. }
  44470. else {
  44471. return;
  44472. }
  44473. this._epsilon = epsilon;
  44474. this._scene = scene;
  44475. this._scene.spriteManagers.push(this);
  44476. var indices = [];
  44477. var index = 0;
  44478. for (var count = 0; count < capacity; count++) {
  44479. indices.push(index);
  44480. indices.push(index + 1);
  44481. indices.push(index + 2);
  44482. indices.push(index);
  44483. indices.push(index + 2);
  44484. indices.push(index + 3);
  44485. index += 4;
  44486. }
  44487. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44488. // VBO
  44489. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44490. this._vertexData = new Float32Array(capacity * 16 * 4);
  44491. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44492. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44493. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44494. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44495. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44496. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44497. this._vertexBuffers["options"] = options;
  44498. this._vertexBuffers["cellInfo"] = cellInfo;
  44499. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44500. // Effects
  44501. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44502. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44503. }
  44504. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44505. set: function (callback) {
  44506. if (this._onDisposeObserver) {
  44507. this.onDisposeObservable.remove(this._onDisposeObserver);
  44508. }
  44509. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44510. },
  44511. enumerable: true,
  44512. configurable: true
  44513. });
  44514. Object.defineProperty(SpriteManager.prototype, "texture", {
  44515. get: function () {
  44516. return this._spriteTexture;
  44517. },
  44518. set: function (value) {
  44519. this._spriteTexture = value;
  44520. },
  44521. enumerable: true,
  44522. configurable: true
  44523. });
  44524. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44525. var arrayOffset = index * 16;
  44526. if (offsetX === 0)
  44527. offsetX = this._epsilon;
  44528. else if (offsetX === 1)
  44529. offsetX = 1 - this._epsilon;
  44530. if (offsetY === 0)
  44531. offsetY = this._epsilon;
  44532. else if (offsetY === 1)
  44533. offsetY = 1 - this._epsilon;
  44534. this._vertexData[arrayOffset] = sprite.position.x;
  44535. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44536. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44537. this._vertexData[arrayOffset + 3] = sprite.angle;
  44538. this._vertexData[arrayOffset + 4] = sprite.width;
  44539. this._vertexData[arrayOffset + 5] = sprite.height;
  44540. this._vertexData[arrayOffset + 6] = offsetX;
  44541. this._vertexData[arrayOffset + 7] = offsetY;
  44542. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44543. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44544. var offset = (sprite.cellIndex / rowSize) >> 0;
  44545. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44546. this._vertexData[arrayOffset + 11] = offset;
  44547. // Color
  44548. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44549. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44550. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44551. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44552. };
  44553. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44554. var count = Math.min(this._capacity, this.sprites.length);
  44555. var min = BABYLON.Vector3.Zero();
  44556. var max = BABYLON.Vector3.Zero();
  44557. var distance = Number.MAX_VALUE;
  44558. var currentSprite = null;
  44559. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44560. var cameraView = camera.getViewMatrix();
  44561. for (var index = 0; index < count; index++) {
  44562. var sprite = this.sprites[index];
  44563. if (!sprite) {
  44564. continue;
  44565. }
  44566. if (predicate) {
  44567. if (!predicate(sprite)) {
  44568. continue;
  44569. }
  44570. }
  44571. else if (!sprite.isPickable) {
  44572. continue;
  44573. }
  44574. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44575. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44576. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44577. if (ray.intersectsBoxMinMax(min, max)) {
  44578. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44579. if (distance > currentDistance) {
  44580. distance = currentDistance;
  44581. currentSprite = sprite;
  44582. if (fastCheck) {
  44583. break;
  44584. }
  44585. }
  44586. }
  44587. }
  44588. if (currentSprite) {
  44589. var result = new BABYLON.PickingInfo();
  44590. result.hit = true;
  44591. result.pickedSprite = currentSprite;
  44592. result.distance = distance;
  44593. return result;
  44594. }
  44595. return null;
  44596. };
  44597. SpriteManager.prototype.render = function () {
  44598. // Check
  44599. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44600. return;
  44601. var engine = this._scene.getEngine();
  44602. var baseSize = this._spriteTexture.getBaseSize();
  44603. // Sprites
  44604. var deltaTime = engine.getDeltaTime();
  44605. var max = Math.min(this._capacity, this.sprites.length);
  44606. var rowSize = baseSize.width / this.cellWidth;
  44607. var offset = 0;
  44608. for (var index = 0; index < max; index++) {
  44609. var sprite = this.sprites[index];
  44610. if (!sprite) {
  44611. continue;
  44612. }
  44613. sprite._animate(deltaTime);
  44614. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44615. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44616. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44617. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44618. }
  44619. this._buffer.update(this._vertexData);
  44620. // Render
  44621. var effect = this._effectBase;
  44622. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44623. effect = this._effectFog;
  44624. }
  44625. engine.enableEffect(effect);
  44626. var viewMatrix = this._scene.getViewMatrix();
  44627. effect.setTexture("diffuseSampler", this._spriteTexture);
  44628. effect.setMatrix("view", viewMatrix);
  44629. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44630. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44631. // Fog
  44632. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44633. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44634. effect.setColor3("vFogColor", this._scene.fogColor);
  44635. }
  44636. // VBOs
  44637. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44638. // Draw order
  44639. engine.setDepthFunctionToLessOrEqual();
  44640. effect.setBool("alphaTest", true);
  44641. engine.setColorWrite(false);
  44642. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44643. engine.setColorWrite(true);
  44644. effect.setBool("alphaTest", false);
  44645. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44646. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44647. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44648. };
  44649. SpriteManager.prototype.dispose = function () {
  44650. if (this._buffer) {
  44651. this._buffer.dispose();
  44652. this._buffer = null;
  44653. }
  44654. if (this._indexBuffer) {
  44655. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44656. this._indexBuffer = null;
  44657. }
  44658. if (this._spriteTexture) {
  44659. this._spriteTexture.dispose();
  44660. this._spriteTexture = null;
  44661. }
  44662. // Remove from scene
  44663. var index = this._scene.spriteManagers.indexOf(this);
  44664. this._scene.spriteManagers.splice(index, 1);
  44665. // Callback
  44666. this.onDisposeObservable.notifyObservers(this);
  44667. this.onDisposeObservable.clear();
  44668. };
  44669. return SpriteManager;
  44670. }());
  44671. BABYLON.SpriteManager = SpriteManager;
  44672. })(BABYLON || (BABYLON = {}));
  44673. //# sourceMappingURL=babylon.spriteManager.js.map
  44674. var BABYLON;
  44675. (function (BABYLON) {
  44676. var Sprite = /** @class */ (function () {
  44677. function Sprite(name, manager) {
  44678. this.name = name;
  44679. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44680. this.width = 1.0;
  44681. this.height = 1.0;
  44682. this.angle = 0;
  44683. this.cellIndex = 0;
  44684. this.invertU = 0;
  44685. this.invertV = 0;
  44686. this.animations = new Array();
  44687. this.isPickable = false;
  44688. this._animationStarted = false;
  44689. this._loopAnimation = false;
  44690. this._fromIndex = 0;
  44691. this._toIndex = 0;
  44692. this._delay = 0;
  44693. this._direction = 1;
  44694. this._time = 0;
  44695. this._manager = manager;
  44696. this._manager.sprites.push(this);
  44697. this.position = BABYLON.Vector3.Zero();
  44698. }
  44699. Object.defineProperty(Sprite.prototype, "size", {
  44700. get: function () {
  44701. return this.width;
  44702. },
  44703. set: function (value) {
  44704. this.width = value;
  44705. this.height = value;
  44706. },
  44707. enumerable: true,
  44708. configurable: true
  44709. });
  44710. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44711. this._fromIndex = from;
  44712. this._toIndex = to;
  44713. this._loopAnimation = loop;
  44714. this._delay = delay;
  44715. this._animationStarted = true;
  44716. this._direction = from < to ? 1 : -1;
  44717. this.cellIndex = from;
  44718. this._time = 0;
  44719. this._onAnimationEnd = onAnimationEnd;
  44720. };
  44721. Sprite.prototype.stopAnimation = function () {
  44722. this._animationStarted = false;
  44723. };
  44724. Sprite.prototype._animate = function (deltaTime) {
  44725. if (!this._animationStarted)
  44726. return;
  44727. this._time += deltaTime;
  44728. if (this._time > this._delay) {
  44729. this._time = this._time % this._delay;
  44730. this.cellIndex += this._direction;
  44731. if (this.cellIndex > this._toIndex) {
  44732. if (this._loopAnimation) {
  44733. this.cellIndex = this._fromIndex;
  44734. }
  44735. else {
  44736. this.cellIndex = this._toIndex;
  44737. this._animationStarted = false;
  44738. if (this._onAnimationEnd) {
  44739. this._onAnimationEnd();
  44740. }
  44741. if (this.disposeWhenFinishedAnimating) {
  44742. this.dispose();
  44743. }
  44744. }
  44745. }
  44746. }
  44747. };
  44748. Sprite.prototype.dispose = function () {
  44749. for (var i = 0; i < this._manager.sprites.length; i++) {
  44750. if (this._manager.sprites[i] == this) {
  44751. this._manager.sprites.splice(i, 1);
  44752. }
  44753. }
  44754. };
  44755. return Sprite;
  44756. }());
  44757. BABYLON.Sprite = Sprite;
  44758. })(BABYLON || (BABYLON = {}));
  44759. //# sourceMappingURL=babylon.sprite.js.map
  44760. var BABYLON;
  44761. (function (BABYLON) {
  44762. var IntersectionInfo = /** @class */ (function () {
  44763. function IntersectionInfo(bu, bv, distance) {
  44764. this.bu = bu;
  44765. this.bv = bv;
  44766. this.distance = distance;
  44767. this.faceId = 0;
  44768. this.subMeshId = 0;
  44769. }
  44770. return IntersectionInfo;
  44771. }());
  44772. BABYLON.IntersectionInfo = IntersectionInfo;
  44773. var PickingInfo = /** @class */ (function () {
  44774. function PickingInfo() {
  44775. this.hit = false;
  44776. this.distance = 0;
  44777. this.pickedPoint = null;
  44778. this.pickedMesh = null;
  44779. this.bu = 0;
  44780. this.bv = 0;
  44781. this.faceId = -1;
  44782. this.subMeshId = 0;
  44783. this.pickedSprite = null;
  44784. }
  44785. // Methods
  44786. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44787. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44788. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44789. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44790. return null;
  44791. }
  44792. var indices = this.pickedMesh.getIndices();
  44793. if (!indices) {
  44794. return null;
  44795. }
  44796. var result;
  44797. if (useVerticesNormals) {
  44798. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44799. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44800. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44801. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44802. normal0 = normal0.scale(this.bu);
  44803. normal1 = normal1.scale(this.bv);
  44804. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44805. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44806. }
  44807. else {
  44808. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44809. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44810. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44811. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44812. var p1p2 = vertex1.subtract(vertex2);
  44813. var p3p2 = vertex3.subtract(vertex2);
  44814. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44815. }
  44816. if (useWorldCoordinates) {
  44817. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44818. }
  44819. return BABYLON.Vector3.Normalize(result);
  44820. };
  44821. PickingInfo.prototype.getTextureCoordinates = function () {
  44822. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44823. return null;
  44824. }
  44825. var indices = this.pickedMesh.getIndices();
  44826. if (!indices) {
  44827. return null;
  44828. }
  44829. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44830. if (!uvs) {
  44831. return null;
  44832. }
  44833. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44834. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44835. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44836. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44837. uv1 = uv1.scale(this.bu);
  44838. uv2 = uv2.scale(this.bv);
  44839. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44840. };
  44841. return PickingInfo;
  44842. }());
  44843. BABYLON.PickingInfo = PickingInfo;
  44844. })(BABYLON || (BABYLON = {}));
  44845. //# sourceMappingURL=babylon.pickingInfo.js.map
  44846. var BABYLON;
  44847. (function (BABYLON) {
  44848. var Ray = /** @class */ (function () {
  44849. function Ray(origin, direction, length) {
  44850. if (length === void 0) { length = Number.MAX_VALUE; }
  44851. this.origin = origin;
  44852. this.direction = direction;
  44853. this.length = length;
  44854. }
  44855. // Methods
  44856. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44857. var d = 0.0;
  44858. var maxValue = Number.MAX_VALUE;
  44859. var inv;
  44860. var min;
  44861. var max;
  44862. var temp;
  44863. if (Math.abs(this.direction.x) < 0.0000001) {
  44864. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44865. return false;
  44866. }
  44867. }
  44868. else {
  44869. inv = 1.0 / this.direction.x;
  44870. min = (minimum.x - this.origin.x) * inv;
  44871. max = (maximum.x - this.origin.x) * inv;
  44872. if (max === -Infinity) {
  44873. max = Infinity;
  44874. }
  44875. if (min > max) {
  44876. temp = min;
  44877. min = max;
  44878. max = temp;
  44879. }
  44880. d = Math.max(min, d);
  44881. maxValue = Math.min(max, maxValue);
  44882. if (d > maxValue) {
  44883. return false;
  44884. }
  44885. }
  44886. if (Math.abs(this.direction.y) < 0.0000001) {
  44887. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44888. return false;
  44889. }
  44890. }
  44891. else {
  44892. inv = 1.0 / this.direction.y;
  44893. min = (minimum.y - this.origin.y) * inv;
  44894. max = (maximum.y - this.origin.y) * inv;
  44895. if (max === -Infinity) {
  44896. max = Infinity;
  44897. }
  44898. if (min > max) {
  44899. temp = min;
  44900. min = max;
  44901. max = temp;
  44902. }
  44903. d = Math.max(min, d);
  44904. maxValue = Math.min(max, maxValue);
  44905. if (d > maxValue) {
  44906. return false;
  44907. }
  44908. }
  44909. if (Math.abs(this.direction.z) < 0.0000001) {
  44910. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44911. return false;
  44912. }
  44913. }
  44914. else {
  44915. inv = 1.0 / this.direction.z;
  44916. min = (minimum.z - this.origin.z) * inv;
  44917. max = (maximum.z - this.origin.z) * inv;
  44918. if (max === -Infinity) {
  44919. max = Infinity;
  44920. }
  44921. if (min > max) {
  44922. temp = min;
  44923. min = max;
  44924. max = temp;
  44925. }
  44926. d = Math.max(min, d);
  44927. maxValue = Math.min(max, maxValue);
  44928. if (d > maxValue) {
  44929. return false;
  44930. }
  44931. }
  44932. return true;
  44933. };
  44934. Ray.prototype.intersectsBox = function (box) {
  44935. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44936. };
  44937. Ray.prototype.intersectsSphere = function (sphere) {
  44938. var x = sphere.center.x - this.origin.x;
  44939. var y = sphere.center.y - this.origin.y;
  44940. var z = sphere.center.z - this.origin.z;
  44941. var pyth = (x * x) + (y * y) + (z * z);
  44942. var rr = sphere.radius * sphere.radius;
  44943. if (pyth <= rr) {
  44944. return true;
  44945. }
  44946. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44947. if (dot < 0.0) {
  44948. return false;
  44949. }
  44950. var temp = pyth - (dot * dot);
  44951. return temp <= rr;
  44952. };
  44953. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44954. if (!this._edge1) {
  44955. this._edge1 = BABYLON.Vector3.Zero();
  44956. this._edge2 = BABYLON.Vector3.Zero();
  44957. this._pvec = BABYLON.Vector3.Zero();
  44958. this._tvec = BABYLON.Vector3.Zero();
  44959. this._qvec = BABYLON.Vector3.Zero();
  44960. }
  44961. vertex1.subtractToRef(vertex0, this._edge1);
  44962. vertex2.subtractToRef(vertex0, this._edge2);
  44963. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44964. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44965. if (det === 0) {
  44966. return null;
  44967. }
  44968. var invdet = 1 / det;
  44969. this.origin.subtractToRef(vertex0, this._tvec);
  44970. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44971. if (bu < 0 || bu > 1.0) {
  44972. return null;
  44973. }
  44974. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44975. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44976. if (bv < 0 || bu + bv > 1.0) {
  44977. return null;
  44978. }
  44979. //check if the distance is longer than the predefined length.
  44980. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44981. if (distance > this.length) {
  44982. return null;
  44983. }
  44984. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44985. };
  44986. Ray.prototype.intersectsPlane = function (plane) {
  44987. var distance;
  44988. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44989. if (Math.abs(result1) < 9.99999997475243E-07) {
  44990. return null;
  44991. }
  44992. else {
  44993. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44994. distance = (-plane.d - result2) / result1;
  44995. if (distance < 0.0) {
  44996. if (distance < -9.99999997475243E-07) {
  44997. return null;
  44998. }
  44999. else {
  45000. return 0;
  45001. }
  45002. }
  45003. return distance;
  45004. }
  45005. };
  45006. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45007. var tm = BABYLON.Tmp.Matrix[0];
  45008. mesh.getWorldMatrix().invertToRef(tm);
  45009. if (this._tmpRay) {
  45010. Ray.TransformToRef(this, tm, this._tmpRay);
  45011. }
  45012. else {
  45013. this._tmpRay = Ray.Transform(this, tm);
  45014. }
  45015. return mesh.intersects(this._tmpRay, fastCheck);
  45016. };
  45017. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45018. if (results) {
  45019. results.length = 0;
  45020. }
  45021. else {
  45022. results = [];
  45023. }
  45024. for (var i = 0; i < meshes.length; i++) {
  45025. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45026. if (pickInfo.hit) {
  45027. results.push(pickInfo);
  45028. }
  45029. }
  45030. results.sort(this._comparePickingInfo);
  45031. return results;
  45032. };
  45033. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45034. if (pickingInfoA.distance < pickingInfoB.distance) {
  45035. return -1;
  45036. }
  45037. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45038. return 1;
  45039. }
  45040. else {
  45041. return 0;
  45042. }
  45043. };
  45044. /**
  45045. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45046. * @param sega the first point of the segment to test the intersection against
  45047. * @param segb the second point of the segment to test the intersection against
  45048. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45049. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45050. */
  45051. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45052. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45053. var u = segb.subtract(sega);
  45054. var v = rsegb.subtract(this.origin);
  45055. var w = sega.subtract(this.origin);
  45056. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45057. var b = BABYLON.Vector3.Dot(u, v);
  45058. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45059. var d = BABYLON.Vector3.Dot(u, w);
  45060. var e = BABYLON.Vector3.Dot(v, w);
  45061. var D = a * c - b * b; // always >= 0
  45062. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45063. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45064. // compute the line parameters of the two closest points
  45065. if (D < Ray.smallnum) {
  45066. sN = 0.0; // force using point P0 on segment S1
  45067. sD = 1.0; // to prevent possible division by 0.0 later
  45068. tN = e;
  45069. tD = c;
  45070. }
  45071. else {
  45072. sN = (b * e - c * d);
  45073. tN = (a * e - b * d);
  45074. if (sN < 0.0) {
  45075. sN = 0.0;
  45076. tN = e;
  45077. tD = c;
  45078. }
  45079. else if (sN > sD) {
  45080. sN = sD;
  45081. tN = e + b;
  45082. tD = c;
  45083. }
  45084. }
  45085. if (tN < 0.0) {
  45086. tN = 0.0;
  45087. // recompute sc for this edge
  45088. if (-d < 0.0) {
  45089. sN = 0.0;
  45090. }
  45091. else if (-d > a)
  45092. sN = sD;
  45093. else {
  45094. sN = -d;
  45095. sD = a;
  45096. }
  45097. }
  45098. else if (tN > tD) {
  45099. tN = tD;
  45100. // recompute sc for this edge
  45101. if ((-d + b) < 0.0) {
  45102. sN = 0;
  45103. }
  45104. else if ((-d + b) > a) {
  45105. sN = sD;
  45106. }
  45107. else {
  45108. sN = (-d + b);
  45109. sD = a;
  45110. }
  45111. }
  45112. // finally do the division to get sc and tc
  45113. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45114. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45115. // get the difference of the two closest points
  45116. var qtc = v.multiplyByFloats(tc, tc, tc);
  45117. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45118. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45119. if (isIntersected) {
  45120. return qtc.length();
  45121. }
  45122. return -1;
  45123. };
  45124. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45125. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45126. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45127. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45128. this.direction.normalize();
  45129. return this;
  45130. };
  45131. // Statics
  45132. Ray.Zero = function () {
  45133. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45134. };
  45135. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45136. var result = Ray.Zero();
  45137. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45138. };
  45139. /**
  45140. * 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
  45141. * transformed to the given world matrix.
  45142. * @param origin The origin point
  45143. * @param end The end point
  45144. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45145. */
  45146. Ray.CreateNewFromTo = function (origin, end, world) {
  45147. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45148. var direction = end.subtract(origin);
  45149. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45150. direction.normalize();
  45151. return Ray.Transform(new Ray(origin, direction, length), world);
  45152. };
  45153. Ray.Transform = function (ray, matrix) {
  45154. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45155. Ray.TransformToRef(ray, matrix, result);
  45156. return result;
  45157. };
  45158. Ray.TransformToRef = function (ray, matrix, result) {
  45159. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45160. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45161. result.length = ray.length;
  45162. var dir = result.direction;
  45163. var len = dir.length();
  45164. if (!(len === 0 || len === 1)) {
  45165. var num = 1.0 / len;
  45166. dir.x *= num;
  45167. dir.y *= num;
  45168. dir.z *= num;
  45169. result.length *= len;
  45170. }
  45171. };
  45172. Ray.smallnum = 0.00000001;
  45173. Ray.rayl = 10e8;
  45174. return Ray;
  45175. }());
  45176. BABYLON.Ray = Ray;
  45177. })(BABYLON || (BABYLON = {}));
  45178. //# sourceMappingURL=babylon.ray.js.map
  45179. var BABYLON;
  45180. (function (BABYLON) {
  45181. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45182. if (boxMin.x > sphereCenter.x + sphereRadius)
  45183. return false;
  45184. if (sphereCenter.x - sphereRadius > boxMax.x)
  45185. return false;
  45186. if (boxMin.y > sphereCenter.y + sphereRadius)
  45187. return false;
  45188. if (sphereCenter.y - sphereRadius > boxMax.y)
  45189. return false;
  45190. if (boxMin.z > sphereCenter.z + sphereRadius)
  45191. return false;
  45192. if (sphereCenter.z - sphereRadius > boxMax.z)
  45193. return false;
  45194. return true;
  45195. };
  45196. var getLowestRoot = (function () {
  45197. var result = { root: 0, found: false };
  45198. return function (a, b, c, maxR) {
  45199. result.root = 0;
  45200. result.found = false;
  45201. var determinant = b * b - 4.0 * a * c;
  45202. if (determinant < 0)
  45203. return result;
  45204. var sqrtD = Math.sqrt(determinant);
  45205. var r1 = (-b - sqrtD) / (2.0 * a);
  45206. var r2 = (-b + sqrtD) / (2.0 * a);
  45207. if (r1 > r2) {
  45208. var temp = r2;
  45209. r2 = r1;
  45210. r1 = temp;
  45211. }
  45212. if (r1 > 0 && r1 < maxR) {
  45213. result.root = r1;
  45214. result.found = true;
  45215. return result;
  45216. }
  45217. if (r2 > 0 && r2 < maxR) {
  45218. result.root = r2;
  45219. result.found = true;
  45220. return result;
  45221. }
  45222. return result;
  45223. };
  45224. })();
  45225. var Collider = /** @class */ (function () {
  45226. function Collider() {
  45227. this._collisionPoint = BABYLON.Vector3.Zero();
  45228. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45229. this._tempVector = BABYLON.Vector3.Zero();
  45230. this._tempVector2 = BABYLON.Vector3.Zero();
  45231. this._tempVector3 = BABYLON.Vector3.Zero();
  45232. this._tempVector4 = BABYLON.Vector3.Zero();
  45233. this._edge = BABYLON.Vector3.Zero();
  45234. this._baseToVertex = BABYLON.Vector3.Zero();
  45235. this._destinationPoint = BABYLON.Vector3.Zero();
  45236. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45237. this._displacementVector = BABYLON.Vector3.Zero();
  45238. this._radius = BABYLON.Vector3.One();
  45239. this._retry = 0;
  45240. this._basePointWorld = BABYLON.Vector3.Zero();
  45241. this._velocityWorld = BABYLON.Vector3.Zero();
  45242. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45243. this._collisionMask = -1;
  45244. }
  45245. Object.defineProperty(Collider.prototype, "collisionMask", {
  45246. get: function () {
  45247. return this._collisionMask;
  45248. },
  45249. set: function (mask) {
  45250. this._collisionMask = !isNaN(mask) ? mask : -1;
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45256. /**
  45257. * Gets the plane normal used to compute the sliding response (in local space)
  45258. */
  45259. get: function () {
  45260. return this._slidePlaneNormal;
  45261. },
  45262. enumerable: true,
  45263. configurable: true
  45264. });
  45265. // Methods
  45266. Collider.prototype._initialize = function (source, dir, e) {
  45267. this._velocity = dir;
  45268. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45269. this._basePoint = source;
  45270. source.multiplyToRef(this._radius, this._basePointWorld);
  45271. dir.multiplyToRef(this._radius, this._velocityWorld);
  45272. this._velocityWorldLength = this._velocityWorld.length();
  45273. this._epsilon = e;
  45274. this.collisionFound = false;
  45275. };
  45276. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45277. pa.subtractToRef(point, this._tempVector);
  45278. pb.subtractToRef(point, this._tempVector2);
  45279. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45280. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45281. if (d < 0)
  45282. return false;
  45283. pc.subtractToRef(point, this._tempVector3);
  45284. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45285. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45286. if (d < 0)
  45287. return false;
  45288. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45289. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45290. return d >= 0;
  45291. };
  45292. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45293. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45294. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45295. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45296. return false;
  45297. }
  45298. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45299. return false;
  45300. return true;
  45301. };
  45302. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45303. var t0;
  45304. var embeddedInPlane = false;
  45305. //defensive programming, actually not needed.
  45306. if (!trianglePlaneArray) {
  45307. trianglePlaneArray = [];
  45308. }
  45309. if (!trianglePlaneArray[faceIndex]) {
  45310. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45311. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45312. }
  45313. var trianglePlane = trianglePlaneArray[faceIndex];
  45314. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45315. return;
  45316. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45317. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45318. if (normalDotVelocity == 0) {
  45319. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45320. return;
  45321. embeddedInPlane = true;
  45322. t0 = 0;
  45323. }
  45324. else {
  45325. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45326. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45327. if (t0 > t1) {
  45328. var temp = t1;
  45329. t1 = t0;
  45330. t0 = temp;
  45331. }
  45332. if (t0 > 1.0 || t1 < 0.0)
  45333. return;
  45334. if (t0 < 0)
  45335. t0 = 0;
  45336. if (t0 > 1.0)
  45337. t0 = 1.0;
  45338. }
  45339. this._collisionPoint.copyFromFloats(0, 0, 0);
  45340. var found = false;
  45341. var t = 1.0;
  45342. if (!embeddedInPlane) {
  45343. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45344. this._velocity.scaleToRef(t0, this._tempVector);
  45345. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45346. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45347. found = true;
  45348. t = t0;
  45349. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45350. }
  45351. }
  45352. if (!found) {
  45353. var velocitySquaredLength = this._velocity.lengthSquared();
  45354. var a = velocitySquaredLength;
  45355. this._basePoint.subtractToRef(p1, this._tempVector);
  45356. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45357. var c = this._tempVector.lengthSquared() - 1.0;
  45358. var lowestRoot = getLowestRoot(a, b, c, t);
  45359. if (lowestRoot.found) {
  45360. t = lowestRoot.root;
  45361. found = true;
  45362. this._collisionPoint.copyFrom(p1);
  45363. }
  45364. this._basePoint.subtractToRef(p2, this._tempVector);
  45365. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45366. c = this._tempVector.lengthSquared() - 1.0;
  45367. lowestRoot = getLowestRoot(a, b, c, t);
  45368. if (lowestRoot.found) {
  45369. t = lowestRoot.root;
  45370. found = true;
  45371. this._collisionPoint.copyFrom(p2);
  45372. }
  45373. this._basePoint.subtractToRef(p3, this._tempVector);
  45374. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45375. c = this._tempVector.lengthSquared() - 1.0;
  45376. lowestRoot = getLowestRoot(a, b, c, t);
  45377. if (lowestRoot.found) {
  45378. t = lowestRoot.root;
  45379. found = true;
  45380. this._collisionPoint.copyFrom(p3);
  45381. }
  45382. p2.subtractToRef(p1, this._edge);
  45383. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45384. var edgeSquaredLength = this._edge.lengthSquared();
  45385. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45386. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45387. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45388. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45389. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45390. lowestRoot = getLowestRoot(a, b, c, t);
  45391. if (lowestRoot.found) {
  45392. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45393. if (f >= 0.0 && f <= 1.0) {
  45394. t = lowestRoot.root;
  45395. found = true;
  45396. this._edge.scaleInPlace(f);
  45397. p1.addToRef(this._edge, this._collisionPoint);
  45398. }
  45399. }
  45400. p3.subtractToRef(p2, this._edge);
  45401. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45402. edgeSquaredLength = this._edge.lengthSquared();
  45403. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45404. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45405. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45406. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45407. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45408. lowestRoot = getLowestRoot(a, b, c, t);
  45409. if (lowestRoot.found) {
  45410. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45411. if (f >= 0.0 && f <= 1.0) {
  45412. t = lowestRoot.root;
  45413. found = true;
  45414. this._edge.scaleInPlace(f);
  45415. p2.addToRef(this._edge, this._collisionPoint);
  45416. }
  45417. }
  45418. p1.subtractToRef(p3, this._edge);
  45419. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45420. edgeSquaredLength = this._edge.lengthSquared();
  45421. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45422. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45423. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45424. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45425. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45426. lowestRoot = getLowestRoot(a, b, c, t);
  45427. if (lowestRoot.found) {
  45428. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45429. if (f >= 0.0 && f <= 1.0) {
  45430. t = lowestRoot.root;
  45431. found = true;
  45432. this._edge.scaleInPlace(f);
  45433. p3.addToRef(this._edge, this._collisionPoint);
  45434. }
  45435. }
  45436. }
  45437. if (found) {
  45438. var distToCollision = t * this._velocity.length();
  45439. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45440. if (!this.intersectionPoint) {
  45441. this.intersectionPoint = this._collisionPoint.clone();
  45442. }
  45443. else {
  45444. this.intersectionPoint.copyFrom(this._collisionPoint);
  45445. }
  45446. this._nearestDistance = distToCollision;
  45447. this.collisionFound = true;
  45448. }
  45449. }
  45450. };
  45451. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45452. for (var i = indexStart; i < indexEnd; i += 3) {
  45453. var p1 = pts[indices[i] - decal];
  45454. var p2 = pts[indices[i + 1] - decal];
  45455. var p3 = pts[indices[i + 2] - decal];
  45456. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45457. }
  45458. };
  45459. Collider.prototype._getResponse = function (pos, vel) {
  45460. pos.addToRef(vel, this._destinationPoint);
  45461. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45462. this._basePoint.addToRef(vel, pos);
  45463. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45464. this._slidePlaneNormal.normalize();
  45465. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45466. pos.addInPlace(this._displacementVector);
  45467. this.intersectionPoint.addInPlace(this._displacementVector);
  45468. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45469. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45470. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45471. };
  45472. return Collider;
  45473. }());
  45474. BABYLON.Collider = Collider;
  45475. })(BABYLON || (BABYLON = {}));
  45476. //# sourceMappingURL=babylon.collider.js.map
  45477. var BABYLON;
  45478. (function (BABYLON) {
  45479. //WebWorker code will be inserted to this variable.
  45480. BABYLON.CollisionWorker = "";
  45481. var WorkerTaskType;
  45482. (function (WorkerTaskType) {
  45483. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45484. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45485. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45486. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45487. var WorkerReplyType;
  45488. (function (WorkerReplyType) {
  45489. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45490. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45491. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45492. var CollisionCoordinatorWorker = /** @class */ (function () {
  45493. function CollisionCoordinatorWorker() {
  45494. var _this = this;
  45495. this._scaledPosition = BABYLON.Vector3.Zero();
  45496. this._scaledVelocity = BABYLON.Vector3.Zero();
  45497. this.onMeshUpdated = function (transformNode) {
  45498. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45499. };
  45500. this.onGeometryUpdated = function (geometry) {
  45501. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45502. };
  45503. this._afterRender = function () {
  45504. if (!_this._init)
  45505. return;
  45506. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45507. return;
  45508. }
  45509. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45510. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45511. if (_this._runningUpdated > 4) {
  45512. return;
  45513. }
  45514. ++_this._runningUpdated;
  45515. var payload = {
  45516. updatedMeshes: _this._addUpdateMeshesList,
  45517. updatedGeometries: _this._addUpdateGeometriesList,
  45518. removedGeometries: _this._toRemoveGeometryArray,
  45519. removedMeshes: _this._toRemoveMeshesArray
  45520. };
  45521. var message = {
  45522. payload: payload,
  45523. taskType: WorkerTaskType.UPDATE
  45524. };
  45525. var serializable = [];
  45526. for (var id in payload.updatedGeometries) {
  45527. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45528. //prepare transferables
  45529. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45530. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45531. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45532. }
  45533. }
  45534. _this._worker.postMessage(message, serializable);
  45535. _this._addUpdateMeshesList = {};
  45536. _this._addUpdateGeometriesList = {};
  45537. _this._toRemoveGeometryArray = [];
  45538. _this._toRemoveMeshesArray = [];
  45539. };
  45540. this._onMessageFromWorker = function (e) {
  45541. var returnData = e.data;
  45542. if (returnData.error != WorkerReplyType.SUCCESS) {
  45543. //TODO what errors can be returned from the worker?
  45544. BABYLON.Tools.Warn("error returned from worker!");
  45545. return;
  45546. }
  45547. switch (returnData.taskType) {
  45548. case WorkerTaskType.INIT:
  45549. _this._init = true;
  45550. //Update the worked with ALL of the scene's current state
  45551. _this._scene.meshes.forEach(function (mesh) {
  45552. _this.onMeshAdded(mesh);
  45553. });
  45554. _this._scene.getGeometries().forEach(function (geometry) {
  45555. _this.onGeometryAdded(geometry);
  45556. });
  45557. break;
  45558. case WorkerTaskType.UPDATE:
  45559. _this._runningUpdated--;
  45560. break;
  45561. case WorkerTaskType.COLLIDE:
  45562. var returnPayload = returnData.payload;
  45563. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45564. return;
  45565. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45566. if (callback) {
  45567. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45568. if (mesh) {
  45569. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45570. }
  45571. }
  45572. //cleanup
  45573. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45574. break;
  45575. }
  45576. };
  45577. this._collisionsCallbackArray = [];
  45578. this._init = false;
  45579. this._runningUpdated = 0;
  45580. this._addUpdateMeshesList = {};
  45581. this._addUpdateGeometriesList = {};
  45582. this._toRemoveGeometryArray = [];
  45583. this._toRemoveMeshesArray = [];
  45584. }
  45585. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45586. if (!this._init)
  45587. return;
  45588. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45589. return;
  45590. position.divideToRef(collider._radius, this._scaledPosition);
  45591. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45592. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45593. var payload = {
  45594. collider: {
  45595. position: this._scaledPosition.asArray(),
  45596. velocity: this._scaledVelocity.asArray(),
  45597. radius: collider._radius.asArray()
  45598. },
  45599. collisionId: collisionIndex,
  45600. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45601. maximumRetry: maximumRetry
  45602. };
  45603. var message = {
  45604. payload: payload,
  45605. taskType: WorkerTaskType.COLLIDE
  45606. };
  45607. this._worker.postMessage(message);
  45608. };
  45609. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45610. this._scene = scene;
  45611. this._scene.registerAfterRender(this._afterRender);
  45612. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45613. this._worker = new Worker(workerUrl);
  45614. this._worker.onmessage = this._onMessageFromWorker;
  45615. var message = {
  45616. payload: {},
  45617. taskType: WorkerTaskType.INIT
  45618. };
  45619. this._worker.postMessage(message);
  45620. };
  45621. CollisionCoordinatorWorker.prototype.destroy = function () {
  45622. this._scene.unregisterAfterRender(this._afterRender);
  45623. this._worker.terminate();
  45624. };
  45625. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45626. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45627. this.onMeshUpdated(mesh);
  45628. };
  45629. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45630. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45631. };
  45632. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45633. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45634. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45635. this.onGeometryUpdated(geometry);
  45636. };
  45637. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45638. this._toRemoveGeometryArray.push(geometry.id);
  45639. };
  45640. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45641. var submeshes = [];
  45642. if (mesh.subMeshes) {
  45643. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45644. var boundingInfo = sm.getBoundingInfo();
  45645. return {
  45646. position: idx,
  45647. verticesStart: sm.verticesStart,
  45648. verticesCount: sm.verticesCount,
  45649. indexStart: sm.indexStart,
  45650. indexCount: sm.indexCount,
  45651. hasMaterial: !!sm.getMaterial(),
  45652. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45653. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45654. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45655. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45656. };
  45657. });
  45658. }
  45659. var geometryId = null;
  45660. if (mesh instanceof BABYLON.Mesh) {
  45661. var geometry = mesh.geometry;
  45662. geometryId = geometry ? geometry.id : null;
  45663. }
  45664. else if (mesh instanceof BABYLON.InstancedMesh) {
  45665. var geometry = mesh.sourceMesh.geometry;
  45666. geometryId = geometry ? geometry.id : null;
  45667. }
  45668. var boundingInfo = mesh.getBoundingInfo();
  45669. return {
  45670. uniqueId: mesh.uniqueId,
  45671. id: mesh.id,
  45672. name: mesh.name,
  45673. geometryId: geometryId,
  45674. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45675. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45676. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45677. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45678. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45679. subMeshes: submeshes,
  45680. checkCollisions: mesh.checkCollisions
  45681. };
  45682. };
  45683. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45684. return {
  45685. id: geometry.id,
  45686. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45687. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45688. indices: new Uint32Array(geometry.getIndices() || []),
  45689. };
  45690. };
  45691. return CollisionCoordinatorWorker;
  45692. }());
  45693. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45694. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45695. function CollisionCoordinatorLegacy() {
  45696. this._scaledPosition = BABYLON.Vector3.Zero();
  45697. this._scaledVelocity = BABYLON.Vector3.Zero();
  45698. this._finalPosition = BABYLON.Vector3.Zero();
  45699. }
  45700. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45701. position.divideToRef(collider._radius, this._scaledPosition);
  45702. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45703. collider.collidedMesh = null;
  45704. collider._retry = 0;
  45705. collider._initialVelocity = this._scaledVelocity;
  45706. collider._initialPosition = this._scaledPosition;
  45707. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45708. this._finalPosition.multiplyInPlace(collider._radius);
  45709. //run the callback
  45710. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45711. };
  45712. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45713. this._scene = scene;
  45714. };
  45715. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45716. //Legacy need no destruction method.
  45717. };
  45718. //No update in legacy mode
  45719. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45720. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45721. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45722. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45723. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45724. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45725. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45726. if (excludedMesh === void 0) { excludedMesh = null; }
  45727. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45728. if (collider._retry >= maximumRetry) {
  45729. finalPosition.copyFrom(position);
  45730. return;
  45731. }
  45732. // Check if this is a mesh else camera or -1
  45733. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  45734. collider._initialize(position, velocity, closeDistance);
  45735. // Check all meshes
  45736. for (var index = 0; index < this._scene.meshes.length; index++) {
  45737. var mesh = this._scene.meshes[index];
  45738. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  45739. mesh._checkCollision(collider);
  45740. }
  45741. }
  45742. if (!collider.collisionFound) {
  45743. position.addToRef(velocity, finalPosition);
  45744. return;
  45745. }
  45746. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  45747. collider._getResponse(position, velocity);
  45748. }
  45749. if (velocity.length() <= closeDistance) {
  45750. finalPosition.copyFrom(position);
  45751. return;
  45752. }
  45753. collider._retry++;
  45754. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  45755. };
  45756. return CollisionCoordinatorLegacy;
  45757. }());
  45758. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  45759. })(BABYLON || (BABYLON = {}));
  45760. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  45761. var BABYLON;
  45762. (function (BABYLON) {
  45763. var Particle = /** @class */ (function () {
  45764. function Particle(particleSystem) {
  45765. this.particleSystem = particleSystem;
  45766. this.position = BABYLON.Vector3.Zero();
  45767. this.direction = BABYLON.Vector3.Zero();
  45768. this.color = new BABYLON.Color4(0, 0, 0, 0);
  45769. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  45770. this.lifeTime = 1.0;
  45771. this.age = 0;
  45772. this.size = 0;
  45773. this.angle = 0;
  45774. this.angularSpeed = 0;
  45775. this._currentFrameCounter = 0;
  45776. this.cellIndex = 0;
  45777. if (!this.particleSystem.isAnimationSheetEnabled) {
  45778. return;
  45779. }
  45780. this.cellIndex = this.particleSystem.startSpriteCellID;
  45781. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45782. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45783. }
  45784. else {
  45785. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45786. }
  45787. }
  45788. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45789. // (ageOffset / scaledUpdateSpeed) / available cells
  45790. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45791. this._currentFrameCounter += scaledUpdateSpeed;
  45792. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45793. this._currentFrameCounter = 0;
  45794. this.cellIndex++;
  45795. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45796. this.cellIndex = this.particleSystem.endSpriteCellID;
  45797. }
  45798. }
  45799. };
  45800. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45801. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45802. this.cellIndex++;
  45803. this._currentFrameCounter = 0;
  45804. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45805. if (this.particleSystem.spriteCellLoop) {
  45806. this.cellIndex = this.particleSystem.startSpriteCellID;
  45807. }
  45808. else {
  45809. this.cellIndex = this.particleSystem.endSpriteCellID;
  45810. }
  45811. }
  45812. }
  45813. else {
  45814. this._currentFrameCounter++;
  45815. }
  45816. };
  45817. Particle.prototype.copyTo = function (other) {
  45818. other.position.copyFrom(this.position);
  45819. other.direction.copyFrom(this.direction);
  45820. other.color.copyFrom(this.color);
  45821. other.colorStep.copyFrom(this.colorStep);
  45822. other.lifeTime = this.lifeTime;
  45823. other.age = this.age;
  45824. other.size = this.size;
  45825. other.angle = this.angle;
  45826. other.angularSpeed = this.angularSpeed;
  45827. other.particleSystem = this.particleSystem;
  45828. other.cellIndex = this.cellIndex;
  45829. };
  45830. return Particle;
  45831. }());
  45832. BABYLON.Particle = Particle;
  45833. })(BABYLON || (BABYLON = {}));
  45834. //# sourceMappingURL=babylon.particle.js.map
  45835. var BABYLON;
  45836. (function (BABYLON) {
  45837. var ParticleSystem = /** @class */ (function () {
  45838. // end of sheet animation
  45839. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45840. if (customEffect === void 0) { customEffect = null; }
  45841. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45842. if (epsilon === void 0) { epsilon = 0.01; }
  45843. var _this = this;
  45844. this.name = name;
  45845. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45846. // Members
  45847. this.animations = [];
  45848. this.renderingGroupId = 0;
  45849. this.emitter = null;
  45850. this.emitRate = 10;
  45851. this.manualEmitCount = -1;
  45852. this.updateSpeed = 0.01;
  45853. this.targetStopDuration = 0;
  45854. this.disposeOnStop = false;
  45855. this.minEmitPower = 1;
  45856. this.maxEmitPower = 1;
  45857. this.minLifeTime = 1;
  45858. this.maxLifeTime = 1;
  45859. this.minSize = 1;
  45860. this.maxSize = 1;
  45861. this.minAngularSpeed = 0;
  45862. this.maxAngularSpeed = 0;
  45863. this.layerMask = 0x0FFFFFFF;
  45864. this.customShader = null;
  45865. this.preventAutoStart = false;
  45866. /**
  45867. * An event triggered when the system is disposed.
  45868. * @type {BABYLON.Observable}
  45869. */
  45870. this.onDisposeObservable = new BABYLON.Observable();
  45871. this.onAnimationEnd = null;
  45872. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45873. this.forceDepthWrite = false;
  45874. this.gravity = BABYLON.Vector3.Zero();
  45875. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45876. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45877. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45878. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45879. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45880. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45881. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45882. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45883. this.particles = new Array();
  45884. this._stockParticles = new Array();
  45885. this._newPartsExcess = 0;
  45886. this._vertexBuffers = {};
  45887. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45888. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45889. this._scaledDirection = BABYLON.Vector3.Zero();
  45890. this._scaledGravity = BABYLON.Vector3.Zero();
  45891. this._currentRenderId = -1;
  45892. this._started = false;
  45893. this._stopped = false;
  45894. this._actualFrame = 0;
  45895. // sheet animation
  45896. this.startSpriteCellID = 0;
  45897. this.endSpriteCellID = 0;
  45898. this.spriteCellLoop = true;
  45899. this.spriteCellChangeSpeed = 0;
  45900. this.spriteCellWidth = 0;
  45901. this.spriteCellHeight = 0;
  45902. this._vertexBufferSize = 11;
  45903. this.appendParticleVertexes = null;
  45904. this.id = name;
  45905. this._capacity = capacity;
  45906. this._epsilon = epsilon;
  45907. if (_isAnimationSheetEnabled) {
  45908. this._vertexBufferSize = 12;
  45909. }
  45910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45911. this._customEffect = customEffect;
  45912. scene.particleSystems.push(this);
  45913. this._createIndexBuffer();
  45914. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45915. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45916. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45917. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45918. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45919. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45920. if (this._isAnimationSheetEnabled) {
  45921. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45922. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45923. }
  45924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45925. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45926. this._vertexBuffers["options"] = options;
  45927. // Default behaviors
  45928. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  45929. this.updateFunction = function (particles) {
  45930. for (var index = 0; index < particles.length; index++) {
  45931. var particle = particles[index];
  45932. particle.age += _this._scaledUpdateSpeed;
  45933. if (particle.age >= particle.lifeTime) {
  45934. _this.recycleParticle(particle);
  45935. index--;
  45936. continue;
  45937. }
  45938. else {
  45939. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45940. particle.color.addInPlace(_this._scaledColorStep);
  45941. if (particle.color.a < 0)
  45942. particle.color.a = 0;
  45943. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45944. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45945. particle.position.addInPlace(_this._scaledDirection);
  45946. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45947. particle.direction.addInPlace(_this._scaledGravity);
  45948. if (_this._isAnimationSheetEnabled) {
  45949. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45950. }
  45951. }
  45952. }
  45953. };
  45954. }
  45955. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45956. set: function (callback) {
  45957. if (this._onDisposeObserver) {
  45958. this.onDisposeObservable.remove(this._onDisposeObserver);
  45959. }
  45960. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45961. },
  45962. enumerable: true,
  45963. configurable: true
  45964. });
  45965. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45966. get: function () {
  45967. return this._isAnimationSheetEnabled;
  45968. },
  45969. enumerable: true,
  45970. configurable: true
  45971. });
  45972. ParticleSystem.prototype._createIndexBuffer = function () {
  45973. var indices = [];
  45974. var index = 0;
  45975. for (var count = 0; count < this._capacity; count++) {
  45976. indices.push(index);
  45977. indices.push(index + 1);
  45978. indices.push(index + 2);
  45979. indices.push(index);
  45980. indices.push(index + 2);
  45981. indices.push(index + 3);
  45982. index += 4;
  45983. }
  45984. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45985. };
  45986. ParticleSystem.prototype.recycleParticle = function (particle) {
  45987. var lastParticle = this.particles.pop();
  45988. if (lastParticle !== particle) {
  45989. lastParticle.copyTo(particle);
  45990. this._stockParticles.push(lastParticle);
  45991. }
  45992. };
  45993. ParticleSystem.prototype.getCapacity = function () {
  45994. return this._capacity;
  45995. };
  45996. ParticleSystem.prototype.isAlive = function () {
  45997. return this._alive;
  45998. };
  45999. ParticleSystem.prototype.isStarted = function () {
  46000. return this._started;
  46001. };
  46002. ParticleSystem.prototype.start = function () {
  46003. this._started = true;
  46004. this._stopped = false;
  46005. this._actualFrame = 0;
  46006. };
  46007. ParticleSystem.prototype.stop = function () {
  46008. this._stopped = true;
  46009. };
  46010. // animation sheet
  46011. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46012. var offset = index * this._vertexBufferSize;
  46013. this._vertexData[offset] = particle.position.x;
  46014. this._vertexData[offset + 1] = particle.position.y;
  46015. this._vertexData[offset + 2] = particle.position.z;
  46016. this._vertexData[offset + 3] = particle.color.r;
  46017. this._vertexData[offset + 4] = particle.color.g;
  46018. this._vertexData[offset + 5] = particle.color.b;
  46019. this._vertexData[offset + 6] = particle.color.a;
  46020. this._vertexData[offset + 7] = particle.angle;
  46021. this._vertexData[offset + 8] = particle.size;
  46022. this._vertexData[offset + 9] = offsetX;
  46023. this._vertexData[offset + 10] = offsetY;
  46024. };
  46025. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46026. if (offsetX === 0)
  46027. offsetX = this._epsilon;
  46028. else if (offsetX === 1)
  46029. offsetX = 1 - this._epsilon;
  46030. if (offsetY === 0)
  46031. offsetY = this._epsilon;
  46032. else if (offsetY === 1)
  46033. offsetY = 1 - this._epsilon;
  46034. var offset = index * this._vertexBufferSize;
  46035. this._vertexData[offset] = particle.position.x;
  46036. this._vertexData[offset + 1] = particle.position.y;
  46037. this._vertexData[offset + 2] = particle.position.z;
  46038. this._vertexData[offset + 3] = particle.color.r;
  46039. this._vertexData[offset + 4] = particle.color.g;
  46040. this._vertexData[offset + 5] = particle.color.b;
  46041. this._vertexData[offset + 6] = particle.color.a;
  46042. this._vertexData[offset + 7] = particle.angle;
  46043. this._vertexData[offset + 8] = particle.size;
  46044. this._vertexData[offset + 9] = offsetX;
  46045. this._vertexData[offset + 10] = offsetY;
  46046. this._vertexData[offset + 11] = particle.cellIndex;
  46047. };
  46048. ParticleSystem.prototype._update = function (newParticles) {
  46049. // Update current
  46050. this._alive = this.particles.length > 0;
  46051. this.updateFunction(this.particles);
  46052. // Add new ones
  46053. var worldMatrix;
  46054. if (this.emitter.position) {
  46055. var emitterMesh = this.emitter;
  46056. worldMatrix = emitterMesh.getWorldMatrix();
  46057. }
  46058. else {
  46059. var emitterPosition = this.emitter;
  46060. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46061. }
  46062. var particle;
  46063. for (var index = 0; index < newParticles; index++) {
  46064. if (this.particles.length === this._capacity) {
  46065. break;
  46066. }
  46067. if (this._stockParticles.length !== 0) {
  46068. particle = this._stockParticles.pop();
  46069. particle.age = 0;
  46070. particle.cellIndex = this.startSpriteCellID;
  46071. }
  46072. else {
  46073. particle = new BABYLON.Particle(this);
  46074. }
  46075. this.particles.push(particle);
  46076. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46077. if (this.startDirectionFunction) {
  46078. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46079. }
  46080. else {
  46081. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46082. }
  46083. if (this.startPositionFunction) {
  46084. this.startPositionFunction(worldMatrix, particle.position, particle);
  46085. }
  46086. else {
  46087. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46088. }
  46089. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46090. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46091. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46092. var step = ParticleSystem.randomNumber(0, 1.0);
  46093. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46094. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46095. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46096. }
  46097. };
  46098. ParticleSystem.prototype._getEffect = function () {
  46099. if (this._customEffect) {
  46100. return this._customEffect;
  46101. }
  46102. ;
  46103. var defines = [];
  46104. if (this._scene.clipPlane) {
  46105. defines.push("#define CLIPPLANE");
  46106. }
  46107. if (this._isAnimationSheetEnabled) {
  46108. defines.push("#define ANIMATESHEET");
  46109. }
  46110. // Effect
  46111. var join = defines.join("\n");
  46112. if (this._cachedDefines !== join) {
  46113. this._cachedDefines = join;
  46114. var attributesNamesOrOptions;
  46115. var effectCreationOption;
  46116. if (this._isAnimationSheetEnabled) {
  46117. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46118. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46119. }
  46120. else {
  46121. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46122. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46123. }
  46124. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46125. }
  46126. return this._effect;
  46127. };
  46128. ParticleSystem.prototype.animate = function () {
  46129. if (!this._started)
  46130. return;
  46131. var effect = this._getEffect();
  46132. // Check
  46133. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46134. return;
  46135. if (this._currentRenderId === this._scene.getRenderId()) {
  46136. return;
  46137. }
  46138. this._currentRenderId = this._scene.getRenderId();
  46139. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46140. // determine the number of particles we need to create
  46141. var newParticles;
  46142. if (this.manualEmitCount > -1) {
  46143. newParticles = this.manualEmitCount;
  46144. this._newPartsExcess = 0;
  46145. this.manualEmitCount = 0;
  46146. }
  46147. else {
  46148. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46149. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46150. }
  46151. if (this._newPartsExcess > 1.0) {
  46152. newParticles += this._newPartsExcess >> 0;
  46153. this._newPartsExcess -= this._newPartsExcess >> 0;
  46154. }
  46155. this._alive = false;
  46156. if (!this._stopped) {
  46157. this._actualFrame += this._scaledUpdateSpeed;
  46158. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46159. this.stop();
  46160. }
  46161. else {
  46162. newParticles = 0;
  46163. }
  46164. this._update(newParticles);
  46165. // Stopped?
  46166. if (this._stopped) {
  46167. if (!this._alive) {
  46168. this._started = false;
  46169. if (this.onAnimationEnd) {
  46170. this.onAnimationEnd();
  46171. }
  46172. if (this.disposeOnStop) {
  46173. this._scene._toBeDisposed.push(this);
  46174. }
  46175. }
  46176. }
  46177. // Animation sheet
  46178. if (this._isAnimationSheetEnabled) {
  46179. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46180. }
  46181. else {
  46182. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46183. }
  46184. // Update VBO
  46185. var offset = 0;
  46186. for (var index = 0; index < this.particles.length; index++) {
  46187. var particle = this.particles[index];
  46188. this.appendParticleVertexes(offset, particle);
  46189. offset += 4;
  46190. }
  46191. if (this._vertexBuffer) {
  46192. this._vertexBuffer.update(this._vertexData);
  46193. }
  46194. };
  46195. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46196. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46197. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46198. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46199. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46200. };
  46201. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46202. this._appendParticleVertex(offset++, particle, 0, 0);
  46203. this._appendParticleVertex(offset++, particle, 1, 0);
  46204. this._appendParticleVertex(offset++, particle, 1, 1);
  46205. this._appendParticleVertex(offset++, particle, 0, 1);
  46206. };
  46207. ParticleSystem.prototype.rebuild = function () {
  46208. this._createIndexBuffer();
  46209. if (this._vertexBuffer) {
  46210. this._vertexBuffer._rebuild();
  46211. }
  46212. };
  46213. ParticleSystem.prototype.render = function () {
  46214. var effect = this._getEffect();
  46215. // Check
  46216. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46217. return 0;
  46218. var engine = this._scene.getEngine();
  46219. // Render
  46220. engine.enableEffect(effect);
  46221. engine.setState(false);
  46222. var viewMatrix = this._scene.getViewMatrix();
  46223. effect.setTexture("diffuseSampler", this.particleTexture);
  46224. effect.setMatrix("view", viewMatrix);
  46225. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46226. if (this._isAnimationSheetEnabled) {
  46227. var baseSize = this.particleTexture.getBaseSize();
  46228. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46229. }
  46230. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46231. if (this._scene.clipPlane) {
  46232. var clipPlane = this._scene.clipPlane;
  46233. var invView = viewMatrix.clone();
  46234. invView.invert();
  46235. effect.setMatrix("invView", invView);
  46236. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46237. }
  46238. // VBOs
  46239. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46240. // Draw order
  46241. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46242. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46243. }
  46244. else {
  46245. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46246. }
  46247. if (this.forceDepthWrite) {
  46248. engine.setDepthWrite(true);
  46249. }
  46250. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46251. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46252. return this.particles.length;
  46253. };
  46254. ParticleSystem.prototype.dispose = function () {
  46255. if (this._vertexBuffer) {
  46256. this._vertexBuffer.dispose();
  46257. this._vertexBuffer = null;
  46258. }
  46259. if (this._indexBuffer) {
  46260. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46261. this._indexBuffer = null;
  46262. }
  46263. if (this.particleTexture) {
  46264. this.particleTexture.dispose();
  46265. this.particleTexture = null;
  46266. }
  46267. // Remove from scene
  46268. var index = this._scene.particleSystems.indexOf(this);
  46269. if (index > -1) {
  46270. this._scene.particleSystems.splice(index, 1);
  46271. }
  46272. // Callback
  46273. this.onDisposeObservable.notifyObservers(this);
  46274. this.onDisposeObservable.clear();
  46275. };
  46276. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46277. if (radius === void 0) { radius = 1; }
  46278. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46279. this.particleEmitterType = particleEmitter;
  46280. return particleEmitter;
  46281. };
  46282. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46283. if (radius === void 0) { radius = 1; }
  46284. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46285. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46286. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46287. this.particleEmitterType = particleEmitter;
  46288. return particleEmitter;
  46289. };
  46290. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46291. if (radius === void 0) { radius = 1; }
  46292. if (angle === void 0) { angle = Math.PI / 4; }
  46293. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46294. this.particleEmitterType = particleEmitter;
  46295. return particleEmitter;
  46296. };
  46297. // 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.
  46298. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46299. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46300. this.direction1 = direction1;
  46301. this.direction2 = direction2;
  46302. this.minEmitBox = minEmitBox;
  46303. this.maxEmitBox = maxEmitBox;
  46304. this.particleEmitterType = particleEmitter;
  46305. return particleEmitter;
  46306. };
  46307. ParticleSystem.randomNumber = function (min, max) {
  46308. if (min === max) {
  46309. return (min);
  46310. }
  46311. var random = Math.random();
  46312. return ((random * (max - min)) + min);
  46313. };
  46314. // Clone
  46315. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46316. var custom = null;
  46317. var program = null;
  46318. if (this.customShader != null) {
  46319. program = this.customShader;
  46320. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46321. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46322. }
  46323. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46324. result.customShader = program;
  46325. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46326. if (newEmitter === undefined) {
  46327. newEmitter = this.emitter;
  46328. }
  46329. result.emitter = newEmitter;
  46330. if (this.particleTexture) {
  46331. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46332. }
  46333. if (!this.preventAutoStart) {
  46334. result.start();
  46335. }
  46336. return result;
  46337. };
  46338. ParticleSystem.prototype.serialize = function () {
  46339. var serializationObject = {};
  46340. serializationObject.name = this.name;
  46341. serializationObject.id = this.id;
  46342. // Emitter
  46343. if (this.emitter.position) {
  46344. var emitterMesh = this.emitter;
  46345. serializationObject.emitterId = emitterMesh.id;
  46346. }
  46347. else {
  46348. var emitterPosition = this.emitter;
  46349. serializationObject.emitter = emitterPosition.asArray();
  46350. }
  46351. serializationObject.capacity = this.getCapacity();
  46352. if (this.particleTexture) {
  46353. serializationObject.textureName = this.particleTexture.name;
  46354. }
  46355. // Animations
  46356. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46357. // Particle system
  46358. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46359. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46360. serializationObject.minSize = this.minSize;
  46361. serializationObject.maxSize = this.maxSize;
  46362. serializationObject.minEmitPower = this.minEmitPower;
  46363. serializationObject.maxEmitPower = this.maxEmitPower;
  46364. serializationObject.minLifeTime = this.minLifeTime;
  46365. serializationObject.maxLifeTime = this.maxLifeTime;
  46366. serializationObject.emitRate = this.emitRate;
  46367. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46368. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46369. serializationObject.gravity = this.gravity.asArray();
  46370. serializationObject.direction1 = this.direction1.asArray();
  46371. serializationObject.direction2 = this.direction2.asArray();
  46372. serializationObject.color1 = this.color1.asArray();
  46373. serializationObject.color2 = this.color2.asArray();
  46374. serializationObject.colorDead = this.colorDead.asArray();
  46375. serializationObject.updateSpeed = this.updateSpeed;
  46376. serializationObject.targetStopDuration = this.targetStopDuration;
  46377. serializationObject.textureMask = this.textureMask.asArray();
  46378. serializationObject.blendMode = this.blendMode;
  46379. serializationObject.customShader = this.customShader;
  46380. serializationObject.preventAutoStart = this.preventAutoStart;
  46381. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46382. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46383. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46384. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46385. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46386. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46387. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46388. return serializationObject;
  46389. };
  46390. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46391. var name = parsedParticleSystem.name;
  46392. var custom = null;
  46393. var program = null;
  46394. if (parsedParticleSystem.customShader) {
  46395. program = parsedParticleSystem.customShader;
  46396. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46397. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46398. }
  46399. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46400. particleSystem.customShader = program;
  46401. if (parsedParticleSystem.id) {
  46402. particleSystem.id = parsedParticleSystem.id;
  46403. }
  46404. // Auto start
  46405. if (parsedParticleSystem.preventAutoStart) {
  46406. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46407. }
  46408. // Texture
  46409. if (parsedParticleSystem.textureName) {
  46410. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46411. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46412. }
  46413. // Emitter
  46414. if (parsedParticleSystem.emitterId) {
  46415. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46416. }
  46417. else {
  46418. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46419. }
  46420. // Animations
  46421. if (parsedParticleSystem.animations) {
  46422. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46423. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46424. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46425. }
  46426. }
  46427. if (parsedParticleSystem.autoAnimate) {
  46428. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46429. }
  46430. // Particle system
  46431. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46432. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46433. particleSystem.minSize = parsedParticleSystem.minSize;
  46434. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46435. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46436. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46437. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46438. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46439. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46440. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46441. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46442. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46443. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46444. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46445. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46446. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46447. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46448. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46449. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46450. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46451. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46452. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46453. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46454. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46455. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46456. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46457. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46458. if (!particleSystem.preventAutoStart) {
  46459. particleSystem.start();
  46460. }
  46461. return particleSystem;
  46462. };
  46463. // Statics
  46464. ParticleSystem.BLENDMODE_ONEONE = 0;
  46465. ParticleSystem.BLENDMODE_STANDARD = 1;
  46466. return ParticleSystem;
  46467. }());
  46468. BABYLON.ParticleSystem = ParticleSystem;
  46469. })(BABYLON || (BABYLON = {}));
  46470. //# sourceMappingURL=babylon.particleSystem.js.map
  46471. var BABYLON;
  46472. (function (BABYLON) {
  46473. var BoxParticleEmitter = /** @class */ (function () {
  46474. // to be updated like the rest of emitters when breaking changes.
  46475. // all property should be come public variables and passed through constructor.
  46476. function BoxParticleEmitter(_particleSystem) {
  46477. this._particleSystem = _particleSystem;
  46478. }
  46479. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46480. get: function () {
  46481. return this._particleSystem.direction1;
  46482. },
  46483. set: function (value) {
  46484. this._particleSystem.direction1 = value;
  46485. },
  46486. enumerable: true,
  46487. configurable: true
  46488. });
  46489. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46490. get: function () {
  46491. return this._particleSystem.direction2;
  46492. },
  46493. set: function (value) {
  46494. this._particleSystem.direction2 = value;
  46495. },
  46496. enumerable: true,
  46497. configurable: true
  46498. });
  46499. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46500. get: function () {
  46501. return this._particleSystem.minEmitBox;
  46502. },
  46503. set: function (value) {
  46504. this._particleSystem.minEmitBox = value;
  46505. },
  46506. enumerable: true,
  46507. configurable: true
  46508. });
  46509. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46510. get: function () {
  46511. return this._particleSystem.maxEmitBox;
  46512. },
  46513. set: function (value) {
  46514. this._particleSystem.maxEmitBox = value;
  46515. },
  46516. enumerable: true,
  46517. configurable: true
  46518. });
  46519. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46520. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46521. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46522. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46523. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46524. };
  46525. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46526. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46527. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46528. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46529. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46530. };
  46531. return BoxParticleEmitter;
  46532. }());
  46533. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46534. })(BABYLON || (BABYLON = {}));
  46535. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46536. var BABYLON;
  46537. (function (BABYLON) {
  46538. var ConeParticleEmitter = /** @class */ (function () {
  46539. function ConeParticleEmitter(radius, angle) {
  46540. this.radius = radius;
  46541. this.angle = angle;
  46542. }
  46543. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46544. if (this.angle === 0) {
  46545. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46546. }
  46547. else {
  46548. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46549. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46550. var randX = Math.cos(phi) * Math.sin(theta);
  46551. var randY = Math.cos(theta);
  46552. var randZ = Math.sin(phi) * Math.sin(theta);
  46553. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46554. }
  46555. };
  46556. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46557. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46558. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46559. var randX = radius * Math.sin(s);
  46560. var randZ = radius * Math.cos(s);
  46561. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46562. };
  46563. return ConeParticleEmitter;
  46564. }());
  46565. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46566. })(BABYLON || (BABYLON = {}));
  46567. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46568. var BABYLON;
  46569. (function (BABYLON) {
  46570. var SphereParticleEmitter = /** @class */ (function () {
  46571. function SphereParticleEmitter(radius) {
  46572. this.radius = radius;
  46573. }
  46574. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46575. // measure the direction Vector from the emitter to the particle.
  46576. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46577. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46578. };
  46579. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46580. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46581. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46582. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46583. var randY = this.radius * Math.cos(theta);
  46584. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46585. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46586. };
  46587. return SphereParticleEmitter;
  46588. }());
  46589. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46590. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46591. __extends(SphereDirectedParticleEmitter, _super);
  46592. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46593. var _this = _super.call(this, radius) || this;
  46594. _this.direction1 = direction1;
  46595. _this.direction2 = direction2;
  46596. return _this;
  46597. }
  46598. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46599. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46600. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46601. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46602. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46603. };
  46604. return SphereDirectedParticleEmitter;
  46605. }(SphereParticleEmitter));
  46606. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46607. })(BABYLON || (BABYLON = {}));
  46608. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46609. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46610. var BABYLON;
  46611. (function (BABYLON) {
  46612. var GPUParticleSystem = /** @class */ (function () {
  46613. function GPUParticleSystem(name, capacity, scene) {
  46614. this.name = name;
  46615. this.emitter = null;
  46616. this.renderingGroupId = 0;
  46617. this.layerMask = 0x0FFFFFFF; // TODO
  46618. this._updateVertexBuffers = {};
  46619. this._renderVertexBuffers = {};
  46620. this._currentRenderId = -1;
  46621. this._started = true;
  46622. /**
  46623. * An event triggered when the system is disposed.
  46624. * @type {BABYLON.Observable}
  46625. */
  46626. this.onDisposeObservable = new BABYLON.Observable();
  46627. this.id = name;
  46628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46629. this._capacity = capacity;
  46630. this._engine = this._scene.getEngine();
  46631. this._scene.particleSystems.push(this);
  46632. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  46633. var updateEffectOptions = {
  46634. attributes: ["position", "age", "life", "velocity"],
  46635. uniformsNames: [],
  46636. uniformBuffersNames: [],
  46637. samplers: [],
  46638. defines: "",
  46639. fallbacks: null,
  46640. onCompiled: null,
  46641. onError: null,
  46642. indexParameters: null,
  46643. maxSimultaneousLights: 0,
  46644. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  46645. };
  46646. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  46647. }
  46648. GPUParticleSystem.prototype.isStarted = function () {
  46649. return this._started;
  46650. };
  46651. GPUParticleSystem.prototype.start = function () {
  46652. this._started = true;
  46653. };
  46654. GPUParticleSystem.prototype.stop = function () {
  46655. this._started = false;
  46656. };
  46657. GPUParticleSystem.prototype.animate = function () {
  46658. // Do nothing
  46659. };
  46660. GPUParticleSystem.prototype._initialize = function () {
  46661. if (this._renderVAO) {
  46662. return;
  46663. }
  46664. var data = new Array();
  46665. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  46666. // position
  46667. data.push(0.0);
  46668. data.push(0.0);
  46669. data.push(0.0);
  46670. var life = 1 + Math.random() * 10; // TODO: var
  46671. data.push(life + 1); // create the particle as a dead one to create a new one at start
  46672. data.push(life);
  46673. // velocity
  46674. data.push(0.0);
  46675. data.push(0.0);
  46676. data.push(0.0);
  46677. }
  46678. // Update VAO
  46679. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46680. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  46681. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  46682. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  46683. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46684. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  46685. this._engine.bindArrayBuffer(null);
  46686. // Render VAO
  46687. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46688. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  46689. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  46690. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  46691. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46692. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  46693. this._engine.bindArrayBuffer(null);
  46694. // Links
  46695. this._sourceVAO = this._updateVAO;
  46696. this._targetVAO = this._renderVAO;
  46697. this._sourceBuffer = this._updateBuffer;
  46698. this._targetBuffer = this._renderBuffer;
  46699. };
  46700. GPUParticleSystem.prototype.render = function () {
  46701. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  46702. return 0;
  46703. }
  46704. // Get everything ready to render
  46705. this._initialize();
  46706. if (this._currentRenderId === this._scene.getRenderId()) {
  46707. return 0;
  46708. }
  46709. this._currentRenderId = this._scene.getRenderId();
  46710. // Enable update effect
  46711. this._engine.enableEffect(this._updateEffect);
  46712. this._engine.setState(false);
  46713. // Bind source VAO
  46714. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  46715. // Update
  46716. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  46717. this._engine.setRasterizerState(false);
  46718. this._engine.beginTransformFeedback();
  46719. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  46720. this._engine.endTransformFeedback();
  46721. this._engine.setRasterizerState(true);
  46722. this._engine.bindTransformFeedbackBuffer(null);
  46723. // Enable render effect
  46724. this._engine.enableEffect(this._renderEffect);
  46725. // Bind source VAO
  46726. this._engine.bindVertexArrayObject(this._targetVAO, null);
  46727. // Render
  46728. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  46729. // Switch VAOs
  46730. var tmpVAO = this._sourceVAO;
  46731. this._sourceVAO = this._targetVAO;
  46732. this._targetVAO = tmpVAO;
  46733. // Switch buffers
  46734. var tmpBuffer = this._sourceBuffer;
  46735. this._sourceBuffer = this._targetBuffer;
  46736. this._targetBuffer = tmpBuffer;
  46737. return 0;
  46738. };
  46739. GPUParticleSystem.prototype.rebuild = function () {
  46740. };
  46741. GPUParticleSystem.prototype.dispose = function () {
  46742. var index = this._scene.particleSystems.indexOf(this);
  46743. if (index > -1) {
  46744. this._scene.particleSystems.splice(index, 1);
  46745. }
  46746. //TODO: this._dataBuffer.dispose();
  46747. // Callback
  46748. this.onDisposeObservable.notifyObservers(this);
  46749. this.onDisposeObservable.clear();
  46750. };
  46751. //TODO: Clone / Parse / serialize
  46752. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  46753. return null;
  46754. };
  46755. GPUParticleSystem.prototype.serialize = function () {
  46756. };
  46757. return GPUParticleSystem;
  46758. }());
  46759. BABYLON.GPUParticleSystem = GPUParticleSystem;
  46760. })(BABYLON || (BABYLON = {}));
  46761. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  46762. var BABYLON;
  46763. (function (BABYLON) {
  46764. var SolidParticle = /** @class */ (function () {
  46765. /**
  46766. * Creates a Solid Particle object.
  46767. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46768. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46769. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46770. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46771. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46772. * `shapeId` (integer) is the model shape identifier in the SPS.
  46773. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46774. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46775. */
  46776. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46777. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46778. this.idx = 0; // particle global index
  46779. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46780. this.position = BABYLON.Vector3.Zero(); // position
  46781. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46782. this.scaling = BABYLON.Vector3.One(); // scaling
  46783. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46784. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46785. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46786. this.alive = true; // alive
  46787. this.isVisible = true; // visibility
  46788. this._pos = 0; // index of this particle in the global "positions" array
  46789. this._ind = 0; // index of this particle in the global "indices" array
  46790. this.shapeId = 0; // model shape id
  46791. this.idxInShape = 0; // index of the particle in its shape id
  46792. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46793. this.idx = particleIndex;
  46794. this._pos = positionIndex;
  46795. this._ind = indiceIndex;
  46796. this._model = model;
  46797. this.shapeId = shapeId;
  46798. this.idxInShape = idxInShape;
  46799. this._sps = sps;
  46800. if (modelBoundingInfo) {
  46801. this._modelBoundingInfo = modelBoundingInfo;
  46802. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46803. }
  46804. }
  46805. Object.defineProperty(SolidParticle.prototype, "scale", {
  46806. /**
  46807. * legacy support, changed scale to scaling
  46808. */
  46809. get: function () {
  46810. return this.scaling;
  46811. },
  46812. set: function (scale) {
  46813. this.scaling = scale;
  46814. },
  46815. enumerable: true,
  46816. configurable: true
  46817. });
  46818. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46819. /**
  46820. * legacy support, changed quaternion to rotationQuaternion
  46821. */
  46822. get: function () {
  46823. return this.rotationQuaternion;
  46824. },
  46825. set: function (q) {
  46826. this.rotationQuaternion = q;
  46827. },
  46828. enumerable: true,
  46829. configurable: true
  46830. });
  46831. /**
  46832. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46833. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46834. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46835. */
  46836. SolidParticle.prototype.intersectsMesh = function (target) {
  46837. if (!this._boundingInfo || !target._boundingInfo) {
  46838. return false;
  46839. }
  46840. if (this._sps._bSphereOnly) {
  46841. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46842. }
  46843. return this._boundingInfo.intersects(target._boundingInfo, false);
  46844. };
  46845. return SolidParticle;
  46846. }());
  46847. BABYLON.SolidParticle = SolidParticle;
  46848. var ModelShape = /** @class */ (function () {
  46849. /**
  46850. * 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.
  46851. * SPS internal tool, don't use it manually.
  46852. */
  46853. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46854. this._indicesLength = 0; // length of the shape in the model indices array
  46855. this.shapeID = id;
  46856. this._shape = shape;
  46857. this._indicesLength = indicesLength;
  46858. this._shapeUV = shapeUV;
  46859. this._positionFunction = posFunction;
  46860. this._vertexFunction = vtxFunction;
  46861. }
  46862. return ModelShape;
  46863. }());
  46864. BABYLON.ModelShape = ModelShape;
  46865. var DepthSortedParticle = /** @class */ (function () {
  46866. function DepthSortedParticle() {
  46867. this.ind = 0; // index of the particle in the "indices" array
  46868. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46869. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46870. }
  46871. return DepthSortedParticle;
  46872. }());
  46873. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46874. })(BABYLON || (BABYLON = {}));
  46875. //# sourceMappingURL=babylon.solidParticle.js.map
  46876. var BABYLON;
  46877. (function (BABYLON) {
  46878. /**
  46879. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46880. */
  46881. var SolidParticleSystem = /** @class */ (function () {
  46882. /**
  46883. * Creates a SPS (Solid Particle System) object.
  46884. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46885. * `scene` (Scene) is the scene in which the SPS is added.
  46886. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  46887. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  46888. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  46889. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  46890. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  46891. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  46892. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  46893. */
  46894. function SolidParticleSystem(name, scene, options) {
  46895. // public members
  46896. /**
  46897. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46898. * Example : var p = SPS.particles[i];
  46899. */
  46900. this.particles = new Array();
  46901. /**
  46902. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46903. */
  46904. this.nbParticles = 0;
  46905. /**
  46906. * If the particles must ever face the camera (default false). Useful for planar particles.
  46907. */
  46908. this.billboard = false;
  46909. /**
  46910. * Recompute normals when adding a shape
  46911. */
  46912. this.recomputeNormals = true;
  46913. /**
  46914. * This a counter ofr your own usage. It's not set by any SPS functions.
  46915. */
  46916. this.counter = 0;
  46917. /**
  46918. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46919. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46920. */
  46921. this.vars = {};
  46922. this._positions = new Array();
  46923. this._indices = new Array();
  46924. this._normals = new Array();
  46925. this._colors = new Array();
  46926. this._uvs = new Array();
  46927. this._index = 0; // indices index
  46928. this._updatable = true;
  46929. this._pickable = false;
  46930. this._isVisibilityBoxLocked = false;
  46931. this._alwaysVisible = false;
  46932. this._depthSort = false;
  46933. this._shapeCounter = 0;
  46934. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  46935. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46936. this._computeParticleColor = true;
  46937. this._computeParticleTexture = true;
  46938. this._computeParticleRotation = true;
  46939. this._computeParticleVertex = false;
  46940. this._computeBoundingBox = false;
  46941. this._depthSortParticles = true;
  46942. this._cam_axisZ = BABYLON.Vector3.Zero();
  46943. this._cam_axisY = BABYLON.Vector3.Zero();
  46944. this._cam_axisX = BABYLON.Vector3.Zero();
  46945. this._axisZ = BABYLON.Axis.Z;
  46946. this._camDir = BABYLON.Vector3.Zero();
  46947. this._camInvertedPosition = BABYLON.Vector3.Zero();
  46948. this._rotMatrix = new BABYLON.Matrix();
  46949. this._invertMatrix = new BABYLON.Matrix();
  46950. this._rotated = BABYLON.Vector3.Zero();
  46951. this._quaternion = new BABYLON.Quaternion();
  46952. this._vertex = BABYLON.Vector3.Zero();
  46953. this._normal = BABYLON.Vector3.Zero();
  46954. this._yaw = 0.0;
  46955. this._pitch = 0.0;
  46956. this._roll = 0.0;
  46957. this._halfroll = 0.0;
  46958. this._halfpitch = 0.0;
  46959. this._halfyaw = 0.0;
  46960. this._sinRoll = 0.0;
  46961. this._cosRoll = 0.0;
  46962. this._sinPitch = 0.0;
  46963. this._cosPitch = 0.0;
  46964. this._sinYaw = 0.0;
  46965. this._cosYaw = 0.0;
  46966. this._mustUnrotateFixedNormals = false;
  46967. this._minimum = BABYLON.Tmp.Vector3[0];
  46968. this._maximum = BABYLON.Tmp.Vector3[1];
  46969. this._minBbox = BABYLON.Tmp.Vector3[4];
  46970. this._maxBbox = BABYLON.Tmp.Vector3[5];
  46971. this._particlesIntersect = false;
  46972. this._depthSortFunction = function (p1, p2) {
  46973. return (p2.sqDistance - p1.sqDistance);
  46974. };
  46975. this._needs32Bits = false;
  46976. this._bSphereOnly = false;
  46977. this._bSphereRadiusFactor = 1.0;
  46978. this.name = name;
  46979. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46980. this._camera = scene.activeCamera;
  46981. this._pickable = options ? options.isPickable : false;
  46982. this._depthSort = options ? options.enableDepthSort : false;
  46983. this._particlesIntersect = options ? options.particleIntersection : false;
  46984. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  46985. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  46986. if (options && options.updatable) {
  46987. this._updatable = options.updatable;
  46988. }
  46989. else {
  46990. this._updatable = true;
  46991. }
  46992. if (this._pickable) {
  46993. this.pickedParticles = [];
  46994. }
  46995. if (this._depthSort) {
  46996. this.depthSortedParticles = [];
  46997. }
  46998. }
  46999. /**
  47000. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47001. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47002. */
  47003. SolidParticleSystem.prototype.buildMesh = function () {
  47004. if (this.nbParticles === 0) {
  47005. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47006. this.addShape(triangle, 1);
  47007. triangle.dispose();
  47008. }
  47009. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47010. this._positions32 = new Float32Array(this._positions);
  47011. this._uvs32 = new Float32Array(this._uvs);
  47012. this._colors32 = new Float32Array(this._colors);
  47013. if (this.recomputeNormals) {
  47014. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  47015. }
  47016. this._normals32 = new Float32Array(this._normals);
  47017. this._fixedNormal32 = new Float32Array(this._normals);
  47018. if (this._mustUnrotateFixedNormals) {
  47019. this._unrotateFixedNormals();
  47020. }
  47021. var vertexData = new BABYLON.VertexData();
  47022. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47023. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47024. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47025. if (this._uvs32) {
  47026. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47027. ;
  47028. }
  47029. if (this._colors32) {
  47030. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47031. }
  47032. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47033. vertexData.applyToMesh(mesh, this._updatable);
  47034. this.mesh = mesh;
  47035. this.mesh.isPickable = this._pickable;
  47036. // free memory
  47037. if (!this._depthSort) {
  47038. this._indices = null;
  47039. }
  47040. this._positions = null;
  47041. this._normals = null;
  47042. this._uvs = null;
  47043. this._colors = null;
  47044. if (!this._updatable) {
  47045. this.particles.length = 0;
  47046. }
  47047. return mesh;
  47048. };
  47049. /**
  47050. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47051. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47052. * Thus the particles generated from `digest()` have their property `position` set yet.
  47053. * `mesh` ( Mesh ) is the mesh to be digested
  47054. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47055. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47056. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47057. */
  47058. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47059. var size = (options && options.facetNb) || 1;
  47060. var number = (options && options.number) || 0;
  47061. var delta = (options && options.delta) || 0;
  47062. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47063. var meshInd = mesh.getIndices();
  47064. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47065. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47066. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47067. var f = 0; // facet counter
  47068. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47069. // compute size from number
  47070. if (number) {
  47071. number = (number > totalFacets) ? totalFacets : number;
  47072. size = Math.round(totalFacets / number);
  47073. delta = 0;
  47074. }
  47075. else {
  47076. size = (size > totalFacets) ? totalFacets : size;
  47077. }
  47078. var facetPos = []; // submesh positions
  47079. var facetInd = []; // submesh indices
  47080. var facetUV = []; // submesh UV
  47081. var facetCol = []; // submesh colors
  47082. var barycenter = BABYLON.Tmp.Vector3[0];
  47083. var sizeO = size;
  47084. while (f < totalFacets) {
  47085. size = sizeO + Math.floor((1 + delta) * Math.random());
  47086. if (f > totalFacets - size) {
  47087. size = totalFacets - f;
  47088. }
  47089. // reset temp arrays
  47090. facetPos.length = 0;
  47091. facetInd.length = 0;
  47092. facetUV.length = 0;
  47093. facetCol.length = 0;
  47094. // iterate over "size" facets
  47095. var fi = 0;
  47096. for (var j = f * 3; j < (f + size) * 3; j++) {
  47097. facetInd.push(fi);
  47098. var i = meshInd[j];
  47099. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47100. if (meshUV) {
  47101. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47102. }
  47103. if (meshCol) {
  47104. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47105. }
  47106. fi++;
  47107. }
  47108. // create a model shape for each single particle
  47109. var idx = this.nbParticles;
  47110. var shape = this._posToShape(facetPos);
  47111. var shapeUV = this._uvsToShapeUV(facetUV);
  47112. // compute the barycenter of the shape
  47113. var v;
  47114. for (v = 0; v < shape.length; v++) {
  47115. barycenter.addInPlace(shape[v]);
  47116. }
  47117. barycenter.scaleInPlace(1 / shape.length);
  47118. // shift the shape from its barycenter to the origin
  47119. for (v = 0; v < shape.length; v++) {
  47120. shape[v].subtractInPlace(barycenter);
  47121. }
  47122. var bInfo;
  47123. if (this._particlesIntersect) {
  47124. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47125. }
  47126. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47127. // add the particle in the SPS
  47128. var currentPos = this._positions.length;
  47129. var currentInd = this._indices.length;
  47130. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47131. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47132. // initialize the particle position
  47133. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47134. this._index += shape.length;
  47135. idx++;
  47136. this.nbParticles++;
  47137. this._shapeCounter++;
  47138. f += size;
  47139. }
  47140. return this;
  47141. };
  47142. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47143. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47144. var index = 0;
  47145. var idx = 0;
  47146. for (var p = 0; p < this.particles.length; p++) {
  47147. this._particle = this.particles[p];
  47148. this._shape = this._particle._model._shape;
  47149. if (this._particle.rotationQuaternion) {
  47150. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47151. }
  47152. else {
  47153. this._yaw = this._particle.rotation.y;
  47154. this._pitch = this._particle.rotation.x;
  47155. this._roll = this._particle.rotation.z;
  47156. this._quaternionRotationYPR();
  47157. }
  47158. this._quaternionToRotationMatrix();
  47159. this._rotMatrix.invertToRef(this._invertMatrix);
  47160. for (var pt = 0; pt < this._shape.length; pt++) {
  47161. idx = index + pt * 3;
  47162. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47163. this._fixedNormal32[idx] = this._normal.x;
  47164. this._fixedNormal32[idx + 1] = this._normal.y;
  47165. this._fixedNormal32[idx + 2] = this._normal.z;
  47166. }
  47167. index = idx + 3;
  47168. }
  47169. };
  47170. //reset copy
  47171. SolidParticleSystem.prototype._resetCopy = function () {
  47172. this._copy.position.x = 0;
  47173. this._copy.position.y = 0;
  47174. this._copy.position.z = 0;
  47175. this._copy.rotation.x = 0;
  47176. this._copy.rotation.y = 0;
  47177. this._copy.rotation.z = 0;
  47178. this._copy.rotationQuaternion = null;
  47179. this._copy.scaling.x = 1.0;
  47180. this._copy.scaling.y = 1.0;
  47181. this._copy.scaling.z = 1.0;
  47182. this._copy.uvs.x = 0;
  47183. this._copy.uvs.y = 0;
  47184. this._copy.uvs.z = 1.0;
  47185. this._copy.uvs.w = 1.0;
  47186. this._copy.color = null;
  47187. };
  47188. // _meshBuilder : inserts the shape model in the global SPS mesh
  47189. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47190. var i;
  47191. var u = 0;
  47192. var c = 0;
  47193. var n = 0;
  47194. this._resetCopy();
  47195. if (options && options.positionFunction) {
  47196. options.positionFunction(this._copy, idx, idxInShape);
  47197. this._mustUnrotateFixedNormals = true;
  47198. }
  47199. if (this._copy.rotationQuaternion) {
  47200. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47201. }
  47202. else {
  47203. this._yaw = this._copy.rotation.y;
  47204. this._pitch = this._copy.rotation.x;
  47205. this._roll = this._copy.rotation.z;
  47206. this._quaternionRotationYPR();
  47207. }
  47208. this._quaternionToRotationMatrix();
  47209. for (i = 0; i < shape.length; i++) {
  47210. this._vertex.x = shape[i].x;
  47211. this._vertex.y = shape[i].y;
  47212. this._vertex.z = shape[i].z;
  47213. if (options && options.vertexFunction) {
  47214. options.vertexFunction(this._copy, this._vertex, i);
  47215. }
  47216. this._vertex.x *= this._copy.scaling.x;
  47217. this._vertex.y *= this._copy.scaling.y;
  47218. this._vertex.z *= this._copy.scaling.z;
  47219. this._vertex.x += this._copy.pivot.x;
  47220. this._vertex.y += this._copy.pivot.y;
  47221. this._vertex.z += this._copy.pivot.z;
  47222. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47223. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47224. if (meshUV) {
  47225. 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);
  47226. u += 2;
  47227. }
  47228. if (this._copy.color) {
  47229. this._color = this._copy.color;
  47230. }
  47231. else if (meshCol && meshCol[c] !== undefined) {
  47232. this._color.r = meshCol[c];
  47233. this._color.g = meshCol[c + 1];
  47234. this._color.b = meshCol[c + 2];
  47235. this._color.a = meshCol[c + 3];
  47236. }
  47237. else {
  47238. this._color.r = 1.0;
  47239. this._color.g = 1.0;
  47240. this._color.b = 1.0;
  47241. this._color.a = 1.0;
  47242. }
  47243. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47244. c += 4;
  47245. if (!this.recomputeNormals && meshNor) {
  47246. this._normal.x = meshNor[n];
  47247. this._normal.y = meshNor[n + 1];
  47248. this._normal.z = meshNor[n + 2];
  47249. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47250. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47251. n += 3;
  47252. }
  47253. }
  47254. for (i = 0; i < meshInd.length; i++) {
  47255. var current_ind = p + meshInd[i];
  47256. indices.push(current_ind);
  47257. if (current_ind > 65535) {
  47258. this._needs32Bits = true;
  47259. }
  47260. }
  47261. if (this._pickable) {
  47262. var nbfaces = meshInd.length / 3;
  47263. for (i = 0; i < nbfaces; i++) {
  47264. this.pickedParticles.push({ idx: idx, faceId: i });
  47265. }
  47266. }
  47267. if (this._depthSort) {
  47268. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47269. }
  47270. return this._copy;
  47271. };
  47272. // returns a shape array from positions array
  47273. SolidParticleSystem.prototype._posToShape = function (positions) {
  47274. var shape = [];
  47275. for (var i = 0; i < positions.length; i += 3) {
  47276. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47277. }
  47278. return shape;
  47279. };
  47280. // returns a shapeUV array from a Vector4 uvs
  47281. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47282. var shapeUV = [];
  47283. if (uvs) {
  47284. for (var i = 0; i < uvs.length; i++)
  47285. shapeUV.push(uvs[i]);
  47286. }
  47287. return shapeUV;
  47288. };
  47289. // adds a new particle object in the particles array
  47290. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47291. if (bInfo === void 0) { bInfo = null; }
  47292. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47293. this.particles.push(sp);
  47294. return sp;
  47295. };
  47296. /**
  47297. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47298. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47299. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47300. * `nb` (positive integer) the number of particles to be created from this model
  47301. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47302. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47303. */
  47304. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47305. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47306. var meshInd = mesh.getIndices();
  47307. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47308. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47309. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47310. var bbInfo;
  47311. if (this._particlesIntersect) {
  47312. bbInfo = mesh.getBoundingInfo();
  47313. }
  47314. var shape = this._posToShape(meshPos);
  47315. var shapeUV = this._uvsToShapeUV(meshUV);
  47316. var posfunc = options ? options.positionFunction : null;
  47317. var vtxfunc = options ? options.vertexFunction : null;
  47318. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47319. // particles
  47320. var sp;
  47321. var currentCopy;
  47322. var idx = this.nbParticles;
  47323. for (var i = 0; i < nb; i++) {
  47324. var currentPos = this._positions.length;
  47325. var currentInd = this._indices.length;
  47326. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47327. if (this._updatable) {
  47328. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47329. sp.position.copyFrom(currentCopy.position);
  47330. sp.rotation.copyFrom(currentCopy.rotation);
  47331. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47332. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47333. }
  47334. if (currentCopy.color && sp.color) {
  47335. sp.color.copyFrom(currentCopy.color);
  47336. }
  47337. sp.scaling.copyFrom(currentCopy.scaling);
  47338. sp.uvs.copyFrom(currentCopy.uvs);
  47339. }
  47340. this._index += shape.length;
  47341. idx++;
  47342. }
  47343. this.nbParticles += nb;
  47344. this._shapeCounter++;
  47345. return this._shapeCounter - 1;
  47346. };
  47347. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47348. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47349. this._resetCopy();
  47350. if (particle._model._positionFunction) {
  47351. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47352. }
  47353. if (this._copy.rotationQuaternion) {
  47354. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47355. }
  47356. else {
  47357. this._yaw = this._copy.rotation.y;
  47358. this._pitch = this._copy.rotation.x;
  47359. this._roll = this._copy.rotation.z;
  47360. this._quaternionRotationYPR();
  47361. }
  47362. this._quaternionToRotationMatrix();
  47363. this._shape = particle._model._shape;
  47364. for (var pt = 0; pt < this._shape.length; pt++) {
  47365. this._vertex.x = this._shape[pt].x;
  47366. this._vertex.y = this._shape[pt].y;
  47367. this._vertex.z = this._shape[pt].z;
  47368. if (particle._model._vertexFunction) {
  47369. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47370. }
  47371. this._vertex.x *= this._copy.scaling.x;
  47372. this._vertex.y *= this._copy.scaling.y;
  47373. this._vertex.z *= this._copy.scaling.z;
  47374. this._vertex.x += this._copy.pivot.x;
  47375. this._vertex.y += this._copy.pivot.y;
  47376. this._vertex.z += this._copy.pivot.z;
  47377. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47378. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47379. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47380. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47381. }
  47382. particle.position.x = 0.0;
  47383. particle.position.y = 0.0;
  47384. particle.position.z = 0.0;
  47385. particle.rotation.x = 0.0;
  47386. particle.rotation.y = 0.0;
  47387. particle.rotation.z = 0.0;
  47388. particle.rotationQuaternion = null;
  47389. particle.scaling.x = 1.0;
  47390. particle.scaling.y = 1.0;
  47391. particle.scaling.z = 1.0;
  47392. };
  47393. /**
  47394. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47395. * Returns the SPS.
  47396. */
  47397. SolidParticleSystem.prototype.rebuildMesh = function () {
  47398. for (var p = 0; p < this.particles.length; p++) {
  47399. this._rebuildParticle(this.particles[p]);
  47400. }
  47401. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47402. return this;
  47403. };
  47404. /**
  47405. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47406. * This method calls `updateParticle()` for each particle of the SPS.
  47407. * For an animated SPS, it is usually called within the render loop.
  47408. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47409. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47410. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47411. * Returns the SPS.
  47412. */
  47413. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47414. if (start === void 0) { start = 0; }
  47415. if (end === void 0) { end = this.nbParticles - 1; }
  47416. if (update === void 0) { update = true; }
  47417. if (!this._updatable) {
  47418. return this;
  47419. }
  47420. // custom beforeUpdate
  47421. this.beforeUpdateParticles(start, end, update);
  47422. this._cam_axisX.x = 1.0;
  47423. this._cam_axisX.y = 0.0;
  47424. this._cam_axisX.z = 0.0;
  47425. this._cam_axisY.x = 0.0;
  47426. this._cam_axisY.y = 1.0;
  47427. this._cam_axisY.z = 0.0;
  47428. this._cam_axisZ.x = 0.0;
  47429. this._cam_axisZ.y = 0.0;
  47430. this._cam_axisZ.z = 1.0;
  47431. // cases when the World Matrix is to be computed first
  47432. if (this.billboard || this._depthSort) {
  47433. this.mesh.computeWorldMatrix(true);
  47434. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47435. }
  47436. // if the particles will always face the camera
  47437. if (this.billboard) {
  47438. // compute the camera position and un-rotate it by the current mesh rotation
  47439. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47440. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47441. this._cam_axisZ.normalize();
  47442. // same for camera up vector extracted from the cam view matrix
  47443. var view = this._camera.getViewMatrix(true);
  47444. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47445. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47446. this._cam_axisY.normalize();
  47447. this._cam_axisX.normalize();
  47448. }
  47449. // if depthSort, compute the camera global position in the mesh local system
  47450. if (this._depthSort) {
  47451. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47452. }
  47453. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47454. var idx = 0; // current position index in the global array positions32
  47455. var index = 0; // position start index in the global array positions32 of the current particle
  47456. var colidx = 0; // current color index in the global array colors32
  47457. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47458. var uvidx = 0; // current uv index in the global array uvs32
  47459. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47460. var pt = 0; // current index in the particle model shape
  47461. if (this.mesh.isFacetDataEnabled) {
  47462. this._computeBoundingBox = true;
  47463. }
  47464. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47465. if (this._computeBoundingBox) {
  47466. if (start == 0 && end == this.nbParticles - 1) {
  47467. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47468. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47469. }
  47470. else {
  47471. if (this.mesh._boundingInfo) {
  47472. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47473. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47474. }
  47475. }
  47476. }
  47477. // particle loop
  47478. index = this.particles[start]._pos;
  47479. var vpos = (index / 3) | 0;
  47480. colorIndex = vpos * 4;
  47481. uvIndex = vpos * 2;
  47482. for (var p = start; p <= end; p++) {
  47483. this._particle = this.particles[p];
  47484. this._shape = this._particle._model._shape;
  47485. this._shapeUV = this._particle._model._shapeUV;
  47486. // call to custom user function to update the particle properties
  47487. this.updateParticle(this._particle);
  47488. // camera-particle distance for depth sorting
  47489. if (this._depthSort && this._depthSortParticles) {
  47490. var dsp = this.depthSortedParticles[p];
  47491. dsp.ind = this._particle._ind;
  47492. dsp.indicesLength = this._particle._model._indicesLength;
  47493. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47494. }
  47495. // skip the computations for inactive or already invisible particles
  47496. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47497. // increment indexes for the next particle
  47498. pt = this._shape.length;
  47499. index += pt * 3;
  47500. colorIndex += pt * 4;
  47501. uvIndex += pt * 2;
  47502. continue;
  47503. }
  47504. if (this._particle.isVisible) {
  47505. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47506. // particle rotation matrix
  47507. if (this.billboard) {
  47508. this._particle.rotation.x = 0.0;
  47509. this._particle.rotation.y = 0.0;
  47510. }
  47511. if (this._computeParticleRotation || this.billboard) {
  47512. if (this._particle.rotationQuaternion) {
  47513. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47514. }
  47515. else {
  47516. this._yaw = this._particle.rotation.y;
  47517. this._pitch = this._particle.rotation.x;
  47518. this._roll = this._particle.rotation.z;
  47519. this._quaternionRotationYPR();
  47520. }
  47521. this._quaternionToRotationMatrix();
  47522. }
  47523. // particle vertex loop
  47524. for (pt = 0; pt < this._shape.length; pt++) {
  47525. idx = index + pt * 3;
  47526. colidx = colorIndex + pt * 4;
  47527. uvidx = uvIndex + pt * 2;
  47528. this._vertex.x = this._shape[pt].x;
  47529. this._vertex.y = this._shape[pt].y;
  47530. this._vertex.z = this._shape[pt].z;
  47531. if (this._computeParticleVertex) {
  47532. this.updateParticleVertex(this._particle, this._vertex, pt);
  47533. }
  47534. // positions
  47535. this._vertex.x *= this._particle.scaling.x;
  47536. this._vertex.y *= this._particle.scaling.y;
  47537. this._vertex.z *= this._particle.scaling.z;
  47538. this._vertex.x += this._particle.pivot.x;
  47539. this._vertex.y += this._particle.pivot.y;
  47540. this._vertex.z += this._particle.pivot.z;
  47541. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47542. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47543. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47544. 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;
  47545. 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;
  47546. 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;
  47547. if (this._computeBoundingBox) {
  47548. if (this._positions32[idx] < this._minimum.x) {
  47549. this._minimum.x = this._positions32[idx];
  47550. }
  47551. if (this._positions32[idx] > this._maximum.x) {
  47552. this._maximum.x = this._positions32[idx];
  47553. }
  47554. if (this._positions32[idx + 1] < this._minimum.y) {
  47555. this._minimum.y = this._positions32[idx + 1];
  47556. }
  47557. if (this._positions32[idx + 1] > this._maximum.y) {
  47558. this._maximum.y = this._positions32[idx + 1];
  47559. }
  47560. if (this._positions32[idx + 2] < this._minimum.z) {
  47561. this._minimum.z = this._positions32[idx + 2];
  47562. }
  47563. if (this._positions32[idx + 2] > this._maximum.z) {
  47564. this._maximum.z = this._positions32[idx + 2];
  47565. }
  47566. }
  47567. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47568. if (!this._computeParticleVertex) {
  47569. this._normal.x = this._fixedNormal32[idx];
  47570. this._normal.y = this._fixedNormal32[idx + 1];
  47571. this._normal.z = this._fixedNormal32[idx + 2];
  47572. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47573. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47574. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47575. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47576. 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;
  47577. 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;
  47578. }
  47579. if (this._computeParticleColor && this._particle.color) {
  47580. this._colors32[colidx] = this._particle.color.r;
  47581. this._colors32[colidx + 1] = this._particle.color.g;
  47582. this._colors32[colidx + 2] = this._particle.color.b;
  47583. this._colors32[colidx + 3] = this._particle.color.a;
  47584. }
  47585. if (this._computeParticleTexture) {
  47586. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47587. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47588. }
  47589. }
  47590. }
  47591. else {
  47592. this._particle._stillInvisible = true; // mark the particle as invisible
  47593. for (pt = 0; pt < this._shape.length; pt++) {
  47594. idx = index + pt * 3;
  47595. colidx = colorIndex + pt * 4;
  47596. uvidx = uvIndex + pt * 2;
  47597. this._positions32[idx] = 0.0;
  47598. this._positions32[idx + 1] = 0.0;
  47599. this._positions32[idx + 2] = 0.0;
  47600. this._normals32[idx] = 0.0;
  47601. this._normals32[idx + 1] = 0.0;
  47602. this._normals32[idx + 2] = 0.0;
  47603. if (this._computeParticleColor && this._particle.color) {
  47604. this._colors32[colidx] = this._particle.color.r;
  47605. this._colors32[colidx + 1] = this._particle.color.g;
  47606. this._colors32[colidx + 2] = this._particle.color.b;
  47607. this._colors32[colidx + 3] = this._particle.color.a;
  47608. }
  47609. if (this._computeParticleTexture) {
  47610. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47611. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47612. }
  47613. }
  47614. }
  47615. // if the particle intersections must be computed : update the bbInfo
  47616. if (this._particlesIntersect) {
  47617. var bInfo = this._particle._boundingInfo;
  47618. var bBox = bInfo.boundingBox;
  47619. var bSphere = bInfo.boundingSphere;
  47620. if (!this._bSphereOnly) {
  47621. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47622. for (var b = 0; b < bBox.vectors.length; b++) {
  47623. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47624. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47625. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47626. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47627. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47628. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47629. 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;
  47630. 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;
  47631. 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;
  47632. }
  47633. bBox._update(this.mesh._worldMatrix);
  47634. }
  47635. // place and scale the particle bouding sphere in the SPS local system, then update it
  47636. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47637. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47638. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47639. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47640. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47641. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47642. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47643. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47644. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47645. 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));
  47646. bSphere._update(this.mesh._worldMatrix);
  47647. }
  47648. // increment indexes for the next particle
  47649. index = idx + 3;
  47650. colorIndex = colidx + 4;
  47651. uvIndex = uvidx + 2;
  47652. }
  47653. // if the VBO must be updated
  47654. if (update) {
  47655. if (this._computeParticleColor) {
  47656. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47657. }
  47658. if (this._computeParticleTexture) {
  47659. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47660. }
  47661. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47662. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47663. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47664. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47665. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47666. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  47667. for (var i = 0; i < this._normals32.length; i++) {
  47668. this._fixedNormal32[i] = this._normals32[i];
  47669. }
  47670. }
  47671. if (!this.mesh.areNormalsFrozen) {
  47672. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47673. }
  47674. }
  47675. if (this._depthSort && this._depthSortParticles) {
  47676. this.depthSortedParticles.sort(this._depthSortFunction);
  47677. var dspl = this.depthSortedParticles.length;
  47678. var sorted = 0;
  47679. var lind = 0;
  47680. var sind = 0;
  47681. var sid = 0;
  47682. for (sorted = 0; sorted < dspl; sorted++) {
  47683. lind = this.depthSortedParticles[sorted].indicesLength;
  47684. sind = this.depthSortedParticles[sorted].ind;
  47685. for (var i = 0; i < lind; i++) {
  47686. this._indices32[sid] = this._indices[sind + i];
  47687. sid++;
  47688. }
  47689. }
  47690. this.mesh.updateIndices(this._indices32);
  47691. }
  47692. }
  47693. if (this._computeBoundingBox) {
  47694. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47695. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47696. }
  47697. this.afterUpdateParticles(start, end, update);
  47698. return this;
  47699. };
  47700. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47701. this._halfroll = this._roll * 0.5;
  47702. this._halfpitch = this._pitch * 0.5;
  47703. this._halfyaw = this._yaw * 0.5;
  47704. this._sinRoll = Math.sin(this._halfroll);
  47705. this._cosRoll = Math.cos(this._halfroll);
  47706. this._sinPitch = Math.sin(this._halfpitch);
  47707. this._cosPitch = Math.cos(this._halfpitch);
  47708. this._sinYaw = Math.sin(this._halfyaw);
  47709. this._cosYaw = Math.cos(this._halfyaw);
  47710. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47711. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47712. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47713. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47714. };
  47715. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47716. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47717. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47718. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47719. this._rotMatrix.m[3] = 0;
  47720. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47721. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47722. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47723. this._rotMatrix.m[7] = 0;
  47724. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47725. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47726. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47727. this._rotMatrix.m[11] = 0;
  47728. this._rotMatrix.m[12] = 0;
  47729. this._rotMatrix.m[13] = 0;
  47730. this._rotMatrix.m[14] = 0;
  47731. this._rotMatrix.m[15] = 1.0;
  47732. };
  47733. /**
  47734. * Disposes the SPS.
  47735. * Returns nothing.
  47736. */
  47737. SolidParticleSystem.prototype.dispose = function () {
  47738. this.mesh.dispose();
  47739. this.vars = null;
  47740. // drop references to internal big arrays for the GC
  47741. this._positions = null;
  47742. this._indices = null;
  47743. this._normals = null;
  47744. this._uvs = null;
  47745. this._colors = null;
  47746. this._indices32 = null;
  47747. this._positions32 = null;
  47748. this._normals32 = null;
  47749. this._fixedNormal32 = null;
  47750. this._uvs32 = null;
  47751. this._colors32 = null;
  47752. this.pickedParticles = null;
  47753. };
  47754. /**
  47755. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47756. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47757. * Returns the SPS.
  47758. */
  47759. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47760. if (!this._isVisibilityBoxLocked) {
  47761. this.mesh.refreshBoundingInfo();
  47762. }
  47763. return this;
  47764. };
  47765. /**
  47766. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47767. * @param size the size (float) of the visibility box
  47768. * note : this doesn't lock the SPS mesh bounding box.
  47769. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47770. */
  47771. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47772. var vis = size / 2;
  47773. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47774. };
  47775. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47776. // getter and setter
  47777. get: function () {
  47778. return this._alwaysVisible;
  47779. },
  47780. /**
  47781. * Sets the SPS as always visible or not
  47782. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47783. */
  47784. set: function (val) {
  47785. this._alwaysVisible = val;
  47786. this.mesh.alwaysSelectAsActiveMesh = val;
  47787. },
  47788. enumerable: true,
  47789. configurable: true
  47790. });
  47791. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47792. get: function () {
  47793. return this._isVisibilityBoxLocked;
  47794. },
  47795. /**
  47796. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47797. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47798. */
  47799. set: function (val) {
  47800. this._isVisibilityBoxLocked = val;
  47801. var boundingInfo = this.mesh.getBoundingInfo();
  47802. boundingInfo.isLocked = val;
  47803. },
  47804. enumerable: true,
  47805. configurable: true
  47806. });
  47807. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47808. // getters
  47809. get: function () {
  47810. return this._computeParticleRotation;
  47811. },
  47812. // Optimizer setters
  47813. /**
  47814. * Tells to `setParticles()` to compute the particle rotations or not.
  47815. * Default value : true. The SPS is faster when it's set to false.
  47816. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47817. */
  47818. set: function (val) {
  47819. this._computeParticleRotation = val;
  47820. },
  47821. enumerable: true,
  47822. configurable: true
  47823. });
  47824. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47825. get: function () {
  47826. return this._computeParticleColor;
  47827. },
  47828. /**
  47829. * Tells to `setParticles()` to compute the particle colors or not.
  47830. * Default value : true. The SPS is faster when it's set to false.
  47831. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47832. */
  47833. set: function (val) {
  47834. this._computeParticleColor = val;
  47835. },
  47836. enumerable: true,
  47837. configurable: true
  47838. });
  47839. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47840. get: function () {
  47841. return this._computeParticleTexture;
  47842. },
  47843. /**
  47844. * Tells to `setParticles()` to compute the particle textures or not.
  47845. * Default value : true. The SPS is faster when it's set to false.
  47846. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47847. */
  47848. set: function (val) {
  47849. this._computeParticleTexture = val;
  47850. },
  47851. enumerable: true,
  47852. configurable: true
  47853. });
  47854. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47855. get: function () {
  47856. return this._computeParticleVertex;
  47857. },
  47858. /**
  47859. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47860. * Default value : false. The SPS is faster when it's set to false.
  47861. * Note : the particle custom vertex positions aren't stored values.
  47862. */
  47863. set: function (val) {
  47864. this._computeParticleVertex = val;
  47865. },
  47866. enumerable: true,
  47867. configurable: true
  47868. });
  47869. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47870. get: function () {
  47871. return this._computeBoundingBox;
  47872. },
  47873. /**
  47874. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47875. */
  47876. set: function (val) {
  47877. this._computeBoundingBox = val;
  47878. },
  47879. enumerable: true,
  47880. configurable: true
  47881. });
  47882. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  47883. get: function () {
  47884. return this._depthSortParticles;
  47885. },
  47886. /**
  47887. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  47888. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  47889. * Default : `true`
  47890. */
  47891. set: function (val) {
  47892. this._depthSortParticles = val;
  47893. },
  47894. enumerable: true,
  47895. configurable: true
  47896. });
  47897. // =======================================================================
  47898. // Particle behavior logic
  47899. // these following methods may be overwritten by the user to fit his needs
  47900. /**
  47901. * This function does nothing. It may be overwritten to set all the particle first values.
  47902. * The SPS doesn't call this function, you may have to call it by your own.
  47903. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47904. */
  47905. SolidParticleSystem.prototype.initParticles = function () {
  47906. };
  47907. /**
  47908. * This function does nothing. It may be overwritten to recycle a particle.
  47909. * The SPS doesn't call this function, you may have to call it by your own.
  47910. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47911. */
  47912. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47913. return particle;
  47914. };
  47915. /**
  47916. * Updates a particle : this function should be overwritten by the user.
  47917. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47918. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47919. * ex : just set a particle position or velocity and recycle conditions
  47920. */
  47921. SolidParticleSystem.prototype.updateParticle = function (particle) {
  47922. return particle;
  47923. };
  47924. /**
  47925. * Updates a vertex of a particle : it can be overwritten by the user.
  47926. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  47927. * @param particle the current particle
  47928. * @param vertex the current index of the current particle
  47929. * @param pt the index of the current vertex in the particle shape
  47930. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  47931. * ex : just set a vertex particle position
  47932. */
  47933. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47934. return vertex;
  47935. };
  47936. /**
  47937. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47938. * This does nothing and may be overwritten by the user.
  47939. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47940. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47941. * @param update the boolean update value actually passed to setParticles()
  47942. */
  47943. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47944. };
  47945. /**
  47946. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47947. * This will be passed three parameters.
  47948. * This does nothing and may be overwritten by the user.
  47949. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47950. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47951. * @param update the boolean update value actually passed to setParticles()
  47952. */
  47953. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47954. };
  47955. return SolidParticleSystem;
  47956. }());
  47957. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47958. })(BABYLON || (BABYLON = {}));
  47959. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  47960. var BABYLON;
  47961. (function (BABYLON) {
  47962. var ShaderMaterial = /** @class */ (function (_super) {
  47963. __extends(ShaderMaterial, _super);
  47964. function ShaderMaterial(name, scene, shaderPath, options) {
  47965. var _this = _super.call(this, name, scene) || this;
  47966. _this._textures = {};
  47967. _this._textureArrays = {};
  47968. _this._floats = {};
  47969. _this._ints = {};
  47970. _this._floatsArrays = {};
  47971. _this._colors3 = {};
  47972. _this._colors3Arrays = {};
  47973. _this._colors4 = {};
  47974. _this._vectors2 = {};
  47975. _this._vectors3 = {};
  47976. _this._vectors4 = {};
  47977. _this._matrices = {};
  47978. _this._matrices3x3 = {};
  47979. _this._matrices2x2 = {};
  47980. _this._vectors2Arrays = {};
  47981. _this._vectors3Arrays = {};
  47982. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47983. _this._shaderPath = shaderPath;
  47984. options.needAlphaBlending = options.needAlphaBlending || false;
  47985. options.needAlphaTesting = options.needAlphaTesting || false;
  47986. options.attributes = options.attributes || ["position", "normal", "uv"];
  47987. options.uniforms = options.uniforms || ["worldViewProjection"];
  47988. options.uniformBuffers = options.uniformBuffers || [];
  47989. options.samplers = options.samplers || [];
  47990. options.defines = options.defines || [];
  47991. _this._options = options;
  47992. return _this;
  47993. }
  47994. ShaderMaterial.prototype.getClassName = function () {
  47995. return "ShaderMaterial";
  47996. };
  47997. ShaderMaterial.prototype.needAlphaBlending = function () {
  47998. return this._options.needAlphaBlending;
  47999. };
  48000. ShaderMaterial.prototype.needAlphaTesting = function () {
  48001. return this._options.needAlphaTesting;
  48002. };
  48003. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48004. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48005. this._options.uniforms.push(uniformName);
  48006. }
  48007. };
  48008. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48009. if (this._options.samplers.indexOf(name) === -1) {
  48010. this._options.samplers.push(name);
  48011. }
  48012. this._textures[name] = texture;
  48013. return this;
  48014. };
  48015. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48016. if (this._options.samplers.indexOf(name) === -1) {
  48017. this._options.samplers.push(name);
  48018. }
  48019. this._checkUniform(name);
  48020. this._textureArrays[name] = textures;
  48021. return this;
  48022. };
  48023. ShaderMaterial.prototype.setFloat = function (name, value) {
  48024. this._checkUniform(name);
  48025. this._floats[name] = value;
  48026. return this;
  48027. };
  48028. ShaderMaterial.prototype.setInt = function (name, value) {
  48029. this._checkUniform(name);
  48030. this._ints[name] = value;
  48031. return this;
  48032. };
  48033. ShaderMaterial.prototype.setFloats = function (name, value) {
  48034. this._checkUniform(name);
  48035. this._floatsArrays[name] = value;
  48036. return this;
  48037. };
  48038. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48039. this._checkUniform(name);
  48040. this._colors3[name] = value;
  48041. return this;
  48042. };
  48043. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48044. this._checkUniform(name);
  48045. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48046. color.toArray(arr, arr.length);
  48047. return arr;
  48048. }, []);
  48049. return this;
  48050. };
  48051. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48052. this._checkUniform(name);
  48053. this._colors4[name] = value;
  48054. return this;
  48055. };
  48056. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48057. this._checkUniform(name);
  48058. this._vectors2[name] = value;
  48059. return this;
  48060. };
  48061. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48062. this._checkUniform(name);
  48063. this._vectors3[name] = value;
  48064. return this;
  48065. };
  48066. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48067. this._checkUniform(name);
  48068. this._vectors4[name] = value;
  48069. return this;
  48070. };
  48071. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48072. this._checkUniform(name);
  48073. this._matrices[name] = value;
  48074. return this;
  48075. };
  48076. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48077. this._checkUniform(name);
  48078. this._matrices3x3[name] = value;
  48079. return this;
  48080. };
  48081. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48082. this._checkUniform(name);
  48083. this._matrices2x2[name] = value;
  48084. return this;
  48085. };
  48086. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48087. this._checkUniform(name);
  48088. this._vectors2Arrays[name] = value;
  48089. return this;
  48090. };
  48091. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48092. this._checkUniform(name);
  48093. this._vectors3Arrays[name] = value;
  48094. return this;
  48095. };
  48096. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48097. if (!mesh) {
  48098. return true;
  48099. }
  48100. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48101. return false;
  48102. }
  48103. return false;
  48104. };
  48105. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48106. var scene = this.getScene();
  48107. var engine = scene.getEngine();
  48108. if (!this.checkReadyOnEveryCall) {
  48109. if (this._renderId === scene.getRenderId()) {
  48110. if (this._checkCache(scene, mesh, useInstances)) {
  48111. return true;
  48112. }
  48113. }
  48114. }
  48115. // Instances
  48116. var defines = [];
  48117. var attribs = [];
  48118. var fallbacks = new BABYLON.EffectFallbacks();
  48119. if (useInstances) {
  48120. defines.push("#define INSTANCES");
  48121. }
  48122. for (var index = 0; index < this._options.defines.length; index++) {
  48123. defines.push(this._options.defines[index]);
  48124. }
  48125. for (var index = 0; index < this._options.attributes.length; index++) {
  48126. attribs.push(this._options.attributes[index]);
  48127. }
  48128. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48129. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48130. defines.push("#define VERTEXCOLOR");
  48131. }
  48132. // Bones
  48133. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48134. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48135. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48136. if (mesh.numBoneInfluencers > 4) {
  48137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48139. }
  48140. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48141. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48142. fallbacks.addCPUSkinningFallback(0, mesh);
  48143. if (this._options.uniforms.indexOf("mBones") === -1) {
  48144. this._options.uniforms.push("mBones");
  48145. }
  48146. }
  48147. else {
  48148. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48149. }
  48150. // Textures
  48151. for (var name in this._textures) {
  48152. if (!this._textures[name].isReady()) {
  48153. return false;
  48154. }
  48155. }
  48156. // Alpha test
  48157. if (engine.getAlphaTesting()) {
  48158. defines.push("#define ALPHATEST");
  48159. }
  48160. var previousEffect = this._effect;
  48161. var join = defines.join("\n");
  48162. this._effect = engine.createEffect(this._shaderPath, {
  48163. attributes: attribs,
  48164. uniformsNames: this._options.uniforms,
  48165. uniformBuffersNames: this._options.uniformBuffers,
  48166. samplers: this._options.samplers,
  48167. defines: join,
  48168. fallbacks: fallbacks,
  48169. onCompiled: this.onCompiled,
  48170. onError: this.onError
  48171. }, engine);
  48172. if (!this._effect.isReady()) {
  48173. return false;
  48174. }
  48175. if (previousEffect !== this._effect) {
  48176. scene.resetCachedMaterial();
  48177. }
  48178. this._renderId = scene.getRenderId();
  48179. return true;
  48180. };
  48181. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48182. var scene = this.getScene();
  48183. if (!this._effect) {
  48184. return;
  48185. }
  48186. if (this._options.uniforms.indexOf("world") !== -1) {
  48187. this._effect.setMatrix("world", world);
  48188. }
  48189. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48190. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48191. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48192. }
  48193. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48194. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48195. }
  48196. };
  48197. ShaderMaterial.prototype.bind = function (world, mesh) {
  48198. // Std values
  48199. this.bindOnlyWorldMatrix(world);
  48200. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48201. if (this._options.uniforms.indexOf("view") !== -1) {
  48202. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48203. }
  48204. if (this._options.uniforms.indexOf("projection") !== -1) {
  48205. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48206. }
  48207. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48208. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48209. }
  48210. // Bones
  48211. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48212. var name;
  48213. // Texture
  48214. for (name in this._textures) {
  48215. this._effect.setTexture(name, this._textures[name]);
  48216. }
  48217. // Texture arrays
  48218. for (name in this._textureArrays) {
  48219. this._effect.setTextureArray(name, this._textureArrays[name]);
  48220. }
  48221. // Int
  48222. for (name in this._ints) {
  48223. this._effect.setInt(name, this._ints[name]);
  48224. }
  48225. // Float
  48226. for (name in this._floats) {
  48227. this._effect.setFloat(name, this._floats[name]);
  48228. }
  48229. // Floats
  48230. for (name in this._floatsArrays) {
  48231. this._effect.setArray(name, this._floatsArrays[name]);
  48232. }
  48233. // Color3
  48234. for (name in this._colors3) {
  48235. this._effect.setColor3(name, this._colors3[name]);
  48236. }
  48237. for (name in this._colors3Arrays) {
  48238. this._effect.setArray3(name, this._colors3Arrays[name]);
  48239. }
  48240. // Color4
  48241. for (name in this._colors4) {
  48242. var color = this._colors4[name];
  48243. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48244. }
  48245. // Vector2
  48246. for (name in this._vectors2) {
  48247. this._effect.setVector2(name, this._vectors2[name]);
  48248. }
  48249. // Vector3
  48250. for (name in this._vectors3) {
  48251. this._effect.setVector3(name, this._vectors3[name]);
  48252. }
  48253. // Vector4
  48254. for (name in this._vectors4) {
  48255. this._effect.setVector4(name, this._vectors4[name]);
  48256. }
  48257. // Matrix
  48258. for (name in this._matrices) {
  48259. this._effect.setMatrix(name, this._matrices[name]);
  48260. }
  48261. // Matrix 3x3
  48262. for (name in this._matrices3x3) {
  48263. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48264. }
  48265. // Matrix 2x2
  48266. for (name in this._matrices2x2) {
  48267. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48268. }
  48269. // Vector2Array
  48270. for (name in this._vectors2Arrays) {
  48271. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48272. }
  48273. // Vector3Array
  48274. for (name in this._vectors3Arrays) {
  48275. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48276. }
  48277. }
  48278. this._afterBind(mesh);
  48279. };
  48280. ShaderMaterial.prototype.getActiveTextures = function () {
  48281. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48282. for (var name in this._textures) {
  48283. activeTextures.push(this._textures[name]);
  48284. }
  48285. for (var name in this._textureArrays) {
  48286. var array = this._textureArrays[name];
  48287. for (var index = 0; index < array.length; index++) {
  48288. activeTextures.push(array[index]);
  48289. }
  48290. }
  48291. return activeTextures;
  48292. };
  48293. ShaderMaterial.prototype.hasTexture = function (texture) {
  48294. if (_super.prototype.hasTexture.call(this, texture)) {
  48295. return true;
  48296. }
  48297. for (var name in this._textures) {
  48298. if (this._textures[name] === texture) {
  48299. return true;
  48300. }
  48301. }
  48302. for (var name in this._textureArrays) {
  48303. var array = this._textureArrays[name];
  48304. for (var index = 0; index < array.length; index++) {
  48305. if (array[index] === texture) {
  48306. return true;
  48307. }
  48308. }
  48309. }
  48310. return false;
  48311. };
  48312. ShaderMaterial.prototype.clone = function (name) {
  48313. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48314. return newShaderMaterial;
  48315. };
  48316. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48317. if (forceDisposeTextures) {
  48318. var name;
  48319. for (name in this._textures) {
  48320. this._textures[name].dispose();
  48321. }
  48322. for (name in this._textureArrays) {
  48323. var array = this._textureArrays[name];
  48324. for (var index = 0; index < array.length; index++) {
  48325. array[index].dispose();
  48326. }
  48327. }
  48328. }
  48329. this._textures = {};
  48330. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48331. };
  48332. ShaderMaterial.prototype.serialize = function () {
  48333. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48334. serializationObject.customType = "BABYLON.ShaderMaterial";
  48335. serializationObject.options = this._options;
  48336. serializationObject.shaderPath = this._shaderPath;
  48337. var name;
  48338. // Texture
  48339. serializationObject.textures = {};
  48340. for (name in this._textures) {
  48341. serializationObject.textures[name] = this._textures[name].serialize();
  48342. }
  48343. // Texture arrays
  48344. serializationObject.textureArrays = {};
  48345. for (name in this._textureArrays) {
  48346. serializationObject.textureArrays[name] = [];
  48347. var array = this._textureArrays[name];
  48348. for (var index = 0; index < array.length; index++) {
  48349. serializationObject.textureArrays[name].push(array[index].serialize());
  48350. }
  48351. }
  48352. // Float
  48353. serializationObject.floats = {};
  48354. for (name in this._floats) {
  48355. serializationObject.floats[name] = this._floats[name];
  48356. }
  48357. // Float s
  48358. serializationObject.FloatArrays = {};
  48359. for (name in this._floatsArrays) {
  48360. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48361. }
  48362. // Color3
  48363. serializationObject.colors3 = {};
  48364. for (name in this._colors3) {
  48365. serializationObject.colors3[name] = this._colors3[name].asArray();
  48366. }
  48367. // Color3 array
  48368. serializationObject.colors3Arrays = {};
  48369. for (name in this._colors3Arrays) {
  48370. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48371. }
  48372. // Color4
  48373. serializationObject.colors4 = {};
  48374. for (name in this._colors4) {
  48375. serializationObject.colors4[name] = this._colors4[name].asArray();
  48376. }
  48377. // Vector2
  48378. serializationObject.vectors2 = {};
  48379. for (name in this._vectors2) {
  48380. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48381. }
  48382. // Vector3
  48383. serializationObject.vectors3 = {};
  48384. for (name in this._vectors3) {
  48385. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48386. }
  48387. // Vector4
  48388. serializationObject.vectors4 = {};
  48389. for (name in this._vectors4) {
  48390. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48391. }
  48392. // Matrix
  48393. serializationObject.matrices = {};
  48394. for (name in this._matrices) {
  48395. serializationObject.matrices[name] = this._matrices[name].asArray();
  48396. }
  48397. // Matrix 3x3
  48398. serializationObject.matrices3x3 = {};
  48399. for (name in this._matrices3x3) {
  48400. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48401. }
  48402. // Matrix 2x2
  48403. serializationObject.matrices2x2 = {};
  48404. for (name in this._matrices2x2) {
  48405. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48406. }
  48407. // Vector2Array
  48408. serializationObject.vectors2Arrays = {};
  48409. for (name in this._vectors2Arrays) {
  48410. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48411. }
  48412. // Vector3Array
  48413. serializationObject.vectors3Arrays = {};
  48414. for (name in this._vectors3Arrays) {
  48415. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48416. }
  48417. return serializationObject;
  48418. };
  48419. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48420. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48421. var name;
  48422. // Texture
  48423. for (name in source.textures) {
  48424. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48425. }
  48426. // Texture arrays
  48427. for (name in source.textureArrays) {
  48428. var array = source.textureArrays[name];
  48429. var textureArray = new Array();
  48430. for (var index = 0; index < array.length; index++) {
  48431. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48432. }
  48433. material.setTextureArray(name, textureArray);
  48434. }
  48435. // Float
  48436. for (name in source.floats) {
  48437. material.setFloat(name, source.floats[name]);
  48438. }
  48439. // Float s
  48440. for (name in source.floatsArrays) {
  48441. material.setFloats(name, source.floatsArrays[name]);
  48442. }
  48443. // Color3
  48444. for (name in source.colors3) {
  48445. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48446. }
  48447. // Color3 arrays
  48448. for (name in source.colors3Arrays) {
  48449. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48450. if (i % 3 === 0) {
  48451. arr.push([num]);
  48452. }
  48453. else {
  48454. arr[arr.length - 1].push(num);
  48455. }
  48456. return arr;
  48457. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48458. material.setColor3Array(name, colors);
  48459. }
  48460. // Color4
  48461. for (name in source.colors4) {
  48462. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48463. }
  48464. // Vector2
  48465. for (name in source.vectors2) {
  48466. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48467. }
  48468. // Vector3
  48469. for (name in source.vectors3) {
  48470. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48471. }
  48472. // Vector4
  48473. for (name in source.vectors4) {
  48474. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48475. }
  48476. // Matrix
  48477. for (name in source.matrices) {
  48478. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48479. }
  48480. // Matrix 3x3
  48481. for (name in source.matrices3x3) {
  48482. material.setMatrix3x3(name, source.matrices3x3[name]);
  48483. }
  48484. // Matrix 2x2
  48485. for (name in source.matrices2x2) {
  48486. material.setMatrix2x2(name, source.matrices2x2[name]);
  48487. }
  48488. // Vector2Array
  48489. for (name in source.vectors2Arrays) {
  48490. material.setArray2(name, source.vectors2Arrays[name]);
  48491. }
  48492. // Vector3Array
  48493. for (name in source.vectors3Arrays) {
  48494. material.setArray3(name, source.vectors3Arrays[name]);
  48495. }
  48496. return material;
  48497. };
  48498. return ShaderMaterial;
  48499. }(BABYLON.Material));
  48500. BABYLON.ShaderMaterial = ShaderMaterial;
  48501. })(BABYLON || (BABYLON = {}));
  48502. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48503. var BABYLON;
  48504. (function (BABYLON) {
  48505. var GroundMesh = /** @class */ (function (_super) {
  48506. __extends(GroundMesh, _super);
  48507. function GroundMesh(name, scene) {
  48508. var _this = _super.call(this, name, scene) || this;
  48509. _this.generateOctree = false;
  48510. return _this;
  48511. }
  48512. GroundMesh.prototype.getClassName = function () {
  48513. return "GroundMesh";
  48514. };
  48515. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48516. get: function () {
  48517. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48518. },
  48519. enumerable: true,
  48520. configurable: true
  48521. });
  48522. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48523. get: function () {
  48524. return this._subdivisionsX;
  48525. },
  48526. enumerable: true,
  48527. configurable: true
  48528. });
  48529. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48530. get: function () {
  48531. return this._subdivisionsY;
  48532. },
  48533. enumerable: true,
  48534. configurable: true
  48535. });
  48536. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48537. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48538. this._subdivisionsX = chunksCount;
  48539. this._subdivisionsY = chunksCount;
  48540. this.subdivide(chunksCount);
  48541. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48542. };
  48543. /**
  48544. * Returns a height (y) value in the Worl system :
  48545. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48546. * Returns the ground y position if (x, z) are outside the ground surface.
  48547. */
  48548. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48549. var world = this.getWorldMatrix();
  48550. var invMat = BABYLON.Tmp.Matrix[5];
  48551. world.invertToRef(invMat);
  48552. var tmpVect = BABYLON.Tmp.Vector3[8];
  48553. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48554. x = tmpVect.x;
  48555. z = tmpVect.z;
  48556. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48557. return this.position.y;
  48558. }
  48559. if (!this._heightQuads || this._heightQuads.length == 0) {
  48560. this._initHeightQuads();
  48561. this._computeHeightQuads();
  48562. }
  48563. var facet = this._getFacetAt(x, z);
  48564. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48565. // return y in the World system
  48566. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48567. return tmpVect.y;
  48568. };
  48569. /**
  48570. * Returns a normalized vector (Vector3) orthogonal to the ground
  48571. * at the ground coordinates (x, z) expressed in the World system.
  48572. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48573. */
  48574. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48575. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48576. this.getNormalAtCoordinatesToRef(x, z, normal);
  48577. return normal;
  48578. };
  48579. /**
  48580. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48581. * at the ground coordinates (x, z) expressed in the World system.
  48582. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48583. * Returns the GroundMesh.
  48584. */
  48585. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48586. var world = this.getWorldMatrix();
  48587. var tmpMat = BABYLON.Tmp.Matrix[5];
  48588. world.invertToRef(tmpMat);
  48589. var tmpVect = BABYLON.Tmp.Vector3[8];
  48590. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48591. x = tmpVect.x;
  48592. z = tmpVect.z;
  48593. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48594. return this;
  48595. }
  48596. if (!this._heightQuads || this._heightQuads.length == 0) {
  48597. this._initHeightQuads();
  48598. this._computeHeightQuads();
  48599. }
  48600. var facet = this._getFacetAt(x, z);
  48601. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48602. return this;
  48603. };
  48604. /**
  48605. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48606. * if the ground has been updated.
  48607. * This can be used in the render loop.
  48608. * Returns the GroundMesh.
  48609. */
  48610. GroundMesh.prototype.updateCoordinateHeights = function () {
  48611. if (!this._heightQuads || this._heightQuads.length == 0) {
  48612. this._initHeightQuads();
  48613. }
  48614. this._computeHeightQuads();
  48615. return this;
  48616. };
  48617. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48618. GroundMesh.prototype._getFacetAt = function (x, z) {
  48619. // retrieve col and row from x, z coordinates in the ground local system
  48620. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48621. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48622. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48623. var facet;
  48624. if (z < quad.slope.x * x + quad.slope.y) {
  48625. facet = quad.facet1;
  48626. }
  48627. else {
  48628. facet = quad.facet2;
  48629. }
  48630. return facet;
  48631. };
  48632. // Creates and populates the heightMap array with "facet" elements :
  48633. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48634. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48635. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48636. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48637. // Returns the GroundMesh.
  48638. GroundMesh.prototype._initHeightQuads = function () {
  48639. var subdivisionsX = this._subdivisionsX;
  48640. var subdivisionsY = this._subdivisionsY;
  48641. this._heightQuads = new Array();
  48642. for (var row = 0; row < subdivisionsY; row++) {
  48643. for (var col = 0; col < subdivisionsX; col++) {
  48644. 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) };
  48645. this._heightQuads[row * subdivisionsX + col] = quad;
  48646. }
  48647. }
  48648. return this;
  48649. };
  48650. // Compute each quad element values and update the the heightMap array :
  48651. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48652. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48653. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48654. // Returns the GroundMesh.
  48655. GroundMesh.prototype._computeHeightQuads = function () {
  48656. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48657. if (!positions) {
  48658. return this;
  48659. }
  48660. var v1 = BABYLON.Tmp.Vector3[3];
  48661. var v2 = BABYLON.Tmp.Vector3[2];
  48662. var v3 = BABYLON.Tmp.Vector3[1];
  48663. var v4 = BABYLON.Tmp.Vector3[0];
  48664. var v1v2 = BABYLON.Tmp.Vector3[4];
  48665. var v1v3 = BABYLON.Tmp.Vector3[5];
  48666. var v1v4 = BABYLON.Tmp.Vector3[6];
  48667. var norm1 = BABYLON.Tmp.Vector3[7];
  48668. var norm2 = BABYLON.Tmp.Vector3[8];
  48669. var i = 0;
  48670. var j = 0;
  48671. var k = 0;
  48672. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48673. var h = 0;
  48674. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48675. var d2 = 0;
  48676. var subdivisionsX = this._subdivisionsX;
  48677. var subdivisionsY = this._subdivisionsY;
  48678. for (var row = 0; row < subdivisionsY; row++) {
  48679. for (var col = 0; col < subdivisionsX; col++) {
  48680. i = col * 3;
  48681. j = row * (subdivisionsX + 1) * 3;
  48682. k = (row + 1) * (subdivisionsX + 1) * 3;
  48683. v1.x = positions[j + i];
  48684. v1.y = positions[j + i + 1];
  48685. v1.z = positions[j + i + 2];
  48686. v2.x = positions[j + i + 3];
  48687. v2.y = positions[j + i + 4];
  48688. v2.z = positions[j + i + 5];
  48689. v3.x = positions[k + i];
  48690. v3.y = positions[k + i + 1];
  48691. v3.z = positions[k + i + 2];
  48692. v4.x = positions[k + i + 3];
  48693. v4.y = positions[k + i + 4];
  48694. v4.z = positions[k + i + 5];
  48695. // 2D slope V1V4
  48696. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48697. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48698. // facet equations :
  48699. // we compute each facet normal vector
  48700. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48701. // we compute the value d by applying the equation to v1 which belongs to the plane
  48702. // then we store the facet equation in a Vector4
  48703. v2.subtractToRef(v1, v1v2);
  48704. v3.subtractToRef(v1, v1v3);
  48705. v4.subtractToRef(v1, v1v4);
  48706. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48707. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48708. norm1.normalize();
  48709. norm2.normalize();
  48710. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48711. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48712. var quad = this._heightQuads[row * subdivisionsX + col];
  48713. quad.slope.copyFromFloats(cd, h);
  48714. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48715. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48716. }
  48717. }
  48718. return this;
  48719. };
  48720. GroundMesh.prototype.serialize = function (serializationObject) {
  48721. _super.prototype.serialize.call(this, serializationObject);
  48722. serializationObject.subdivisionsX = this._subdivisionsX;
  48723. serializationObject.subdivisionsY = this._subdivisionsY;
  48724. serializationObject.minX = this._minX;
  48725. serializationObject.maxX = this._maxX;
  48726. serializationObject.minZ = this._minZ;
  48727. serializationObject.maxZ = this._maxZ;
  48728. serializationObject.width = this._width;
  48729. serializationObject.height = this._height;
  48730. };
  48731. GroundMesh.Parse = function (parsedMesh, scene) {
  48732. var result = new GroundMesh(parsedMesh.name, scene);
  48733. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48734. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48735. result._minX = parsedMesh.minX;
  48736. result._maxX = parsedMesh.maxX;
  48737. result._minZ = parsedMesh.minZ;
  48738. result._maxZ = parsedMesh.maxZ;
  48739. result._width = parsedMesh.width;
  48740. result._height = parsedMesh.height;
  48741. return result;
  48742. };
  48743. return GroundMesh;
  48744. }(BABYLON.Mesh));
  48745. BABYLON.GroundMesh = GroundMesh;
  48746. })(BABYLON || (BABYLON = {}));
  48747. //# sourceMappingURL=babylon.groundMesh.js.map
  48748. var BABYLON;
  48749. (function (BABYLON) {
  48750. /**
  48751. * Creates an instance based on a source mesh.
  48752. */
  48753. var InstancedMesh = /** @class */ (function (_super) {
  48754. __extends(InstancedMesh, _super);
  48755. function InstancedMesh(name, source) {
  48756. var _this = _super.call(this, name, source.getScene()) || this;
  48757. source.instances.push(_this);
  48758. _this._sourceMesh = source;
  48759. _this.position.copyFrom(source.position);
  48760. _this.rotation.copyFrom(source.rotation);
  48761. _this.scaling.copyFrom(source.scaling);
  48762. if (source.rotationQuaternion) {
  48763. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48764. }
  48765. _this.infiniteDistance = source.infiniteDistance;
  48766. _this.setPivotMatrix(source.getPivotMatrix());
  48767. _this.refreshBoundingInfo();
  48768. _this._syncSubMeshes();
  48769. return _this;
  48770. }
  48771. /**
  48772. * Returns the string "InstancedMesh".
  48773. */
  48774. InstancedMesh.prototype.getClassName = function () {
  48775. return "InstancedMesh";
  48776. };
  48777. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48778. // Methods
  48779. get: function () {
  48780. return this._sourceMesh.receiveShadows;
  48781. },
  48782. enumerable: true,
  48783. configurable: true
  48784. });
  48785. Object.defineProperty(InstancedMesh.prototype, "material", {
  48786. get: function () {
  48787. return this._sourceMesh.material;
  48788. },
  48789. enumerable: true,
  48790. configurable: true
  48791. });
  48792. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48793. get: function () {
  48794. return this._sourceMesh.visibility;
  48795. },
  48796. enumerable: true,
  48797. configurable: true
  48798. });
  48799. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48800. get: function () {
  48801. return this._sourceMesh.skeleton;
  48802. },
  48803. enumerable: true,
  48804. configurable: true
  48805. });
  48806. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48807. get: function () {
  48808. return this._sourceMesh.renderingGroupId;
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. /**
  48814. * Returns the total number of vertices (integer).
  48815. */
  48816. InstancedMesh.prototype.getTotalVertices = function () {
  48817. return this._sourceMesh.getTotalVertices();
  48818. };
  48819. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48820. get: function () {
  48821. return this._sourceMesh;
  48822. },
  48823. enumerable: true,
  48824. configurable: true
  48825. });
  48826. /**
  48827. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48828. */
  48829. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48830. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48831. };
  48832. /**
  48833. * Sets the vertex data of the mesh geometry for the requested `kind`.
  48834. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  48835. * The `data` are either a numeric array either a Float32Array.
  48836. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  48837. * 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).
  48838. * Note that a new underlying VertexBuffer object is created each call.
  48839. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  48840. *
  48841. * Possible `kind` values :
  48842. * - BABYLON.VertexBuffer.PositionKind
  48843. * - BABYLON.VertexBuffer.UVKind
  48844. * - BABYLON.VertexBuffer.UV2Kind
  48845. * - BABYLON.VertexBuffer.UV3Kind
  48846. * - BABYLON.VertexBuffer.UV4Kind
  48847. * - BABYLON.VertexBuffer.UV5Kind
  48848. * - BABYLON.VertexBuffer.UV6Kind
  48849. * - BABYLON.VertexBuffer.ColorKind
  48850. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48851. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48852. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48853. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48854. *
  48855. * Returns the Mesh.
  48856. */
  48857. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  48858. if (this.sourceMesh) {
  48859. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  48860. }
  48861. return this.sourceMesh;
  48862. };
  48863. /**
  48864. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  48865. * If the mesh has no geometry, it is simply returned as it is.
  48866. * The `data` are either a numeric array either a Float32Array.
  48867. * No new underlying VertexBuffer object is created.
  48868. * 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.
  48869. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  48870. *
  48871. * Possible `kind` values :
  48872. * - BABYLON.VertexBuffer.PositionKind
  48873. * - BABYLON.VertexBuffer.UVKind
  48874. * - BABYLON.VertexBuffer.UV2Kind
  48875. * - BABYLON.VertexBuffer.UV3Kind
  48876. * - BABYLON.VertexBuffer.UV4Kind
  48877. * - BABYLON.VertexBuffer.UV5Kind
  48878. * - BABYLON.VertexBuffer.UV6Kind
  48879. * - BABYLON.VertexBuffer.ColorKind
  48880. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48881. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48882. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48883. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48884. *
  48885. * Returns the Mesh.
  48886. */
  48887. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  48888. if (this.sourceMesh) {
  48889. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  48890. }
  48891. return this.sourceMesh;
  48892. };
  48893. /**
  48894. * Sets the mesh indices.
  48895. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  48896. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  48897. * This method creates a new index buffer each call.
  48898. * Returns the Mesh.
  48899. */
  48900. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  48901. if (totalVertices === void 0) { totalVertices = null; }
  48902. if (this.sourceMesh) {
  48903. this.sourceMesh.setIndices(indices, totalVertices);
  48904. }
  48905. return this.sourceMesh;
  48906. };
  48907. /**
  48908. * Boolean : True if the mesh owns the requested kind of data.
  48909. */
  48910. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  48911. return this._sourceMesh.isVerticesDataPresent(kind);
  48912. };
  48913. /**
  48914. * Returns an array of indices (IndicesArray).
  48915. */
  48916. InstancedMesh.prototype.getIndices = function () {
  48917. return this._sourceMesh.getIndices();
  48918. };
  48919. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  48920. get: function () {
  48921. return this._sourceMesh._positions;
  48922. },
  48923. enumerable: true,
  48924. configurable: true
  48925. });
  48926. /**
  48927. * Sets a new updated BoundingInfo to the mesh.
  48928. * Returns the mesh.
  48929. */
  48930. InstancedMesh.prototype.refreshBoundingInfo = function () {
  48931. var meshBB = this._sourceMesh.getBoundingInfo();
  48932. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  48933. this._updateBoundingInfo();
  48934. return this;
  48935. };
  48936. InstancedMesh.prototype._preActivate = function () {
  48937. if (this._currentLOD) {
  48938. this._currentLOD._preActivate();
  48939. }
  48940. return this;
  48941. };
  48942. InstancedMesh.prototype._activate = function (renderId) {
  48943. if (this._currentLOD) {
  48944. this._currentLOD._registerInstanceForRenderId(this, renderId);
  48945. }
  48946. return this;
  48947. };
  48948. /**
  48949. * Returns the current associated LOD AbstractMesh.
  48950. */
  48951. InstancedMesh.prototype.getLOD = function (camera) {
  48952. if (!camera) {
  48953. return this;
  48954. }
  48955. var boundingInfo = this.getBoundingInfo();
  48956. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  48957. if (this._currentLOD === this.sourceMesh) {
  48958. return this;
  48959. }
  48960. return this._currentLOD;
  48961. };
  48962. InstancedMesh.prototype._syncSubMeshes = function () {
  48963. this.releaseSubMeshes();
  48964. if (this._sourceMesh.subMeshes) {
  48965. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  48966. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  48967. }
  48968. }
  48969. return this;
  48970. };
  48971. InstancedMesh.prototype._generatePointsArray = function () {
  48972. return this._sourceMesh._generatePointsArray();
  48973. };
  48974. /**
  48975. * Creates a new InstancedMesh from the current mesh.
  48976. * - name (string) : the cloned mesh name
  48977. * - newParent (optional Node) : the optional Node to parent the clone to.
  48978. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  48979. *
  48980. * Returns the clone.
  48981. */
  48982. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  48983. var result = this._sourceMesh.createInstance(name);
  48984. // Deep copy
  48985. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  48986. // Bounding info
  48987. this.refreshBoundingInfo();
  48988. // Parent
  48989. if (newParent) {
  48990. result.parent = newParent;
  48991. }
  48992. if (!doNotCloneChildren) {
  48993. // Children
  48994. for (var index = 0; index < this.getScene().meshes.length; index++) {
  48995. var mesh = this.getScene().meshes[index];
  48996. if (mesh.parent === this) {
  48997. mesh.clone(mesh.name, result);
  48998. }
  48999. }
  49000. }
  49001. result.computeWorldMatrix(true);
  49002. return result;
  49003. };
  49004. /**
  49005. * Disposes the InstancedMesh.
  49006. * Returns nothing.
  49007. */
  49008. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49009. // Remove from mesh
  49010. var index = this._sourceMesh.instances.indexOf(this);
  49011. this._sourceMesh.instances.splice(index, 1);
  49012. _super.prototype.dispose.call(this, doNotRecurse);
  49013. };
  49014. return InstancedMesh;
  49015. }(BABYLON.AbstractMesh));
  49016. BABYLON.InstancedMesh = InstancedMesh;
  49017. })(BABYLON || (BABYLON = {}));
  49018. //# sourceMappingURL=babylon.instancedMesh.js.map
  49019. var BABYLON;
  49020. (function (BABYLON) {
  49021. var LinesMesh = /** @class */ (function (_super) {
  49022. __extends(LinesMesh, _super);
  49023. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49024. if (scene === void 0) { scene = null; }
  49025. if (parent === void 0) { parent = null; }
  49026. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49027. _this.useVertexColor = useVertexColor;
  49028. _this.useVertexAlpha = useVertexAlpha;
  49029. _this.color = new BABYLON.Color3(1, 1, 1);
  49030. _this.alpha = 1;
  49031. if (source) {
  49032. _this.color = source.color.clone();
  49033. _this.alpha = source.alpha;
  49034. _this.useVertexColor = source.useVertexColor;
  49035. _this.useVertexAlpha = source.useVertexAlpha;
  49036. }
  49037. _this._intersectionThreshold = 0.1;
  49038. var defines = [];
  49039. var options = {
  49040. attributes: [BABYLON.VertexBuffer.PositionKind],
  49041. uniforms: ["world", "viewProjection"],
  49042. needAlphaBlending: true,
  49043. defines: defines
  49044. };
  49045. if (useVertexAlpha === false) {
  49046. options.needAlphaBlending = false;
  49047. }
  49048. if (!useVertexColor) {
  49049. options.uniforms.push("color");
  49050. }
  49051. else {
  49052. options.defines.push("#define VERTEXCOLOR");
  49053. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49054. }
  49055. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49056. return _this;
  49057. }
  49058. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49059. /**
  49060. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49061. * This margin is expressed in world space coordinates, so its value may vary.
  49062. * Default value is 0.1
  49063. * @returns the intersection Threshold value.
  49064. */
  49065. get: function () {
  49066. return this._intersectionThreshold;
  49067. },
  49068. /**
  49069. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49070. * This margin is expressed in world space coordinates, so its value may vary.
  49071. * @param value the new threshold to apply
  49072. */
  49073. set: function (value) {
  49074. if (this._intersectionThreshold === value) {
  49075. return;
  49076. }
  49077. this._intersectionThreshold = value;
  49078. if (this.geometry) {
  49079. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49080. }
  49081. },
  49082. enumerable: true,
  49083. configurable: true
  49084. });
  49085. /**
  49086. * Returns the string "LineMesh"
  49087. */
  49088. LinesMesh.prototype.getClassName = function () {
  49089. return "LinesMesh";
  49090. };
  49091. Object.defineProperty(LinesMesh.prototype, "material", {
  49092. get: function () {
  49093. return this._colorShader;
  49094. },
  49095. set: function (value) {
  49096. // Do nothing
  49097. },
  49098. enumerable: true,
  49099. configurable: true
  49100. });
  49101. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49102. get: function () {
  49103. return false;
  49104. },
  49105. enumerable: true,
  49106. configurable: true
  49107. });
  49108. LinesMesh.prototype.createInstance = function (name) {
  49109. throw new Error("LinesMeshes do not support createInstance.");
  49110. };
  49111. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49112. if (!this._geometry) {
  49113. return this;
  49114. }
  49115. // VBOs
  49116. this._geometry._bind(this._colorShader.getEffect());
  49117. // Color
  49118. if (!this.useVertexColor) {
  49119. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49120. }
  49121. return this;
  49122. };
  49123. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49124. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49125. return this;
  49126. }
  49127. var engine = this.getScene().getEngine();
  49128. // Draw order
  49129. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49130. return this;
  49131. };
  49132. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49133. this._colorShader.dispose();
  49134. _super.prototype.dispose.call(this, doNotRecurse);
  49135. };
  49136. /**
  49137. * Returns a new LineMesh object cloned from the current one.
  49138. */
  49139. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49140. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49141. };
  49142. return LinesMesh;
  49143. }(BABYLON.Mesh));
  49144. BABYLON.LinesMesh = LinesMesh;
  49145. })(BABYLON || (BABYLON = {}));
  49146. //# sourceMappingURL=babylon.linesMesh.js.map
  49147. var BABYLON;
  49148. (function (BABYLON) {
  49149. var MeshBuilder = /** @class */ (function () {
  49150. function MeshBuilder() {
  49151. }
  49152. MeshBuilder.updateSideOrientation = function (orientation) {
  49153. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49154. return BABYLON.Mesh.DOUBLESIDE;
  49155. }
  49156. if (orientation === undefined || orientation === null) {
  49157. return BABYLON.Mesh.FRONTSIDE;
  49158. }
  49159. return orientation;
  49160. };
  49161. /**
  49162. * Creates a box mesh.
  49163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49164. * The parameter `size` sets the size (float) of each box side (default 1).
  49165. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49166. * 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).
  49167. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49169. * 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).
  49170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49172. */
  49173. MeshBuilder.CreateBox = function (name, options, scene) {
  49174. if (scene === void 0) { scene = null; }
  49175. var box = new BABYLON.Mesh(name, scene);
  49176. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49177. box._originalBuilderSideOrientation = options.sideOrientation;
  49178. var vertexData = BABYLON.VertexData.CreateBox(options);
  49179. vertexData.applyToMesh(box, options.updatable);
  49180. return box;
  49181. };
  49182. /**
  49183. * Creates a sphere mesh.
  49184. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49185. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49186. * 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`).
  49187. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49188. * 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
  49189. * 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).
  49190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49191. * 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).
  49192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49194. */
  49195. MeshBuilder.CreateSphere = function (name, options, scene) {
  49196. var sphere = new BABYLON.Mesh(name, scene);
  49197. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49198. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49199. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49200. vertexData.applyToMesh(sphere, options.updatable);
  49201. return sphere;
  49202. };
  49203. /**
  49204. * Creates a plane polygonal mesh. By default, this is a disc.
  49205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49206. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49207. * 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.
  49208. * 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
  49209. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49210. * 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).
  49211. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49213. */
  49214. MeshBuilder.CreateDisc = function (name, options, scene) {
  49215. if (scene === void 0) { scene = null; }
  49216. var disc = new BABYLON.Mesh(name, scene);
  49217. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49218. disc._originalBuilderSideOrientation = options.sideOrientation;
  49219. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49220. vertexData.applyToMesh(disc, options.updatable);
  49221. return disc;
  49222. };
  49223. /**
  49224. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49225. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49226. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49227. * 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`).
  49228. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49229. * 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.
  49230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49231. * 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).
  49232. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49234. */
  49235. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49236. var sphere = new BABYLON.Mesh(name, scene);
  49237. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49238. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49239. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49240. vertexData.applyToMesh(sphere, options.updatable);
  49241. return sphere;
  49242. };
  49243. ;
  49244. /**
  49245. * Creates a ribbon mesh.
  49246. * 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.
  49247. *
  49248. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49249. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49250. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49251. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49252. * 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.
  49253. * 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.
  49254. * 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
  49255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49256. * 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).
  49257. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49258. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49259. * 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.
  49260. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49261. * 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
  49262. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49263. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49265. */
  49266. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49267. if (scene === void 0) { scene = null; }
  49268. var pathArray = options.pathArray;
  49269. var closeArray = options.closeArray;
  49270. var closePath = options.closePath;
  49271. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49272. var instance = options.instance;
  49273. var updatable = options.updatable;
  49274. if (instance) {
  49275. // positionFunction : ribbon case
  49276. // only pathArray and sideOrientation parameters are taken into account for positions update
  49277. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49278. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49279. var positionFunction = function (positions) {
  49280. var minlg = pathArray[0].length;
  49281. var i = 0;
  49282. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49283. for (var si = 1; si <= ns; si++) {
  49284. for (var p = 0; p < pathArray.length; p++) {
  49285. var path = pathArray[p];
  49286. var l = path.length;
  49287. minlg = (minlg < l) ? minlg : l;
  49288. var j = 0;
  49289. while (j < minlg) {
  49290. positions[i] = path[j].x;
  49291. positions[i + 1] = path[j].y;
  49292. positions[i + 2] = path[j].z;
  49293. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49294. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49295. }
  49296. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49297. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49298. }
  49299. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49300. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49301. }
  49302. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49303. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49304. }
  49305. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49306. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49307. }
  49308. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49309. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49310. }
  49311. j++;
  49312. i += 3;
  49313. }
  49314. if (instance._closePath) {
  49315. positions[i] = path[0].x;
  49316. positions[i + 1] = path[0].y;
  49317. positions[i + 2] = path[0].z;
  49318. i += 3;
  49319. }
  49320. }
  49321. }
  49322. };
  49323. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49324. positionFunction(positions);
  49325. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49326. instance._boundingInfo.update(instance._worldMatrix);
  49327. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49328. if (options.colors) {
  49329. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49330. for (var c = 0; c < options.colors.length; c++) {
  49331. colors[c * 4] = options.colors[c].r;
  49332. colors[c * 4 + 1] = options.colors[c].g;
  49333. colors[c * 4 + 2] = options.colors[c].b;
  49334. colors[c * 4 + 3] = options.colors[c].a;
  49335. }
  49336. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49337. }
  49338. if (options.uvs) {
  49339. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49340. for (var i = 0; i < options.uvs.length; i++) {
  49341. uvs[i * 2] = options.uvs[i].x;
  49342. uvs[i * 2 + 1] = options.uvs[i].y;
  49343. }
  49344. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49345. }
  49346. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49347. var indices = instance.getIndices();
  49348. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49349. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49350. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49351. if (instance._closePath) {
  49352. var indexFirst = 0;
  49353. var indexLast = 0;
  49354. for (var p = 0; p < pathArray.length; p++) {
  49355. indexFirst = instance._idx[p] * 3;
  49356. if (p + 1 < pathArray.length) {
  49357. indexLast = (instance._idx[p + 1] - 1) * 3;
  49358. }
  49359. else {
  49360. indexLast = normals.length - 3;
  49361. }
  49362. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49363. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49364. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49365. normals[indexLast] = normals[indexFirst];
  49366. normals[indexLast + 1] = normals[indexFirst + 1];
  49367. normals[indexLast + 2] = normals[indexFirst + 2];
  49368. }
  49369. }
  49370. if (!(instance.areNormalsFrozen)) {
  49371. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49372. }
  49373. }
  49374. return instance;
  49375. }
  49376. else {
  49377. var ribbon = new BABYLON.Mesh(name, scene);
  49378. ribbon._originalBuilderSideOrientation = sideOrientation;
  49379. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49380. if (closePath) {
  49381. ribbon._idx = vertexData._idx;
  49382. }
  49383. ribbon._closePath = closePath;
  49384. ribbon._closeArray = closeArray;
  49385. vertexData.applyToMesh(ribbon, updatable);
  49386. return ribbon;
  49387. }
  49388. };
  49389. /**
  49390. * Creates a cylinder or a cone mesh.
  49391. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49392. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49393. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49394. * 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.
  49395. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49396. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49397. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49398. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49399. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49400. * 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).
  49401. * 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
  49402. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49403. * 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
  49404. * 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.
  49405. * If `enclose` is false, a ring surface is one element.
  49406. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49407. * 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
  49408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49409. * 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).
  49410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49412. */
  49413. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49414. var cylinder = new BABYLON.Mesh(name, scene);
  49415. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49416. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49417. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49418. vertexData.applyToMesh(cylinder, options.updatable);
  49419. return cylinder;
  49420. };
  49421. /**
  49422. * Creates a torus mesh.
  49423. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49424. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49425. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49426. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49428. * 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).
  49429. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49431. */
  49432. MeshBuilder.CreateTorus = function (name, options, scene) {
  49433. var torus = new BABYLON.Mesh(name, scene);
  49434. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49435. torus._originalBuilderSideOrientation = options.sideOrientation;
  49436. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49437. vertexData.applyToMesh(torus, options.updatable);
  49438. return torus;
  49439. };
  49440. /**
  49441. * Creates a torus knot mesh.
  49442. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49443. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49444. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49445. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49446. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49448. * 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).
  49449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49451. */
  49452. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49453. var torusKnot = new BABYLON.Mesh(name, scene);
  49454. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49455. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49456. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49457. vertexData.applyToMesh(torusKnot, options.updatable);
  49458. return torusKnot;
  49459. };
  49460. /**
  49461. * Creates a line system mesh.
  49462. * A line system is a pool of many lines gathered in a single mesh.
  49463. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49464. * 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.
  49465. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49466. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49467. * 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
  49468. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49469. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49470. * 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
  49471. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49473. */
  49474. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49475. var instance = options.instance;
  49476. var lines = options.lines;
  49477. var colors = options.colors;
  49478. if (instance) {
  49479. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49480. var vertexColor;
  49481. var lineColors;
  49482. if (colors) {
  49483. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49484. }
  49485. var i = 0;
  49486. var c = 0;
  49487. for (var l = 0; l < lines.length; l++) {
  49488. var points = lines[l];
  49489. for (var p = 0; p < points.length; p++) {
  49490. positions[i] = points[p].x;
  49491. positions[i + 1] = points[p].y;
  49492. positions[i + 2] = points[p].z;
  49493. if (colors && vertexColor) {
  49494. lineColors = colors[l];
  49495. vertexColor[c] = lineColors[p].r;
  49496. vertexColor[c + 1] = lineColors[p].g;
  49497. vertexColor[c + 2] = lineColors[p].b;
  49498. vertexColor[c + 3] = lineColors[p].a;
  49499. c += 4;
  49500. }
  49501. i += 3;
  49502. }
  49503. }
  49504. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49505. if (colors && vertexColor) {
  49506. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49507. }
  49508. return instance;
  49509. }
  49510. // line system creation
  49511. var useVertexColor = (colors) ? true : false;
  49512. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49513. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49514. vertexData.applyToMesh(lineSystem, options.updatable);
  49515. return lineSystem;
  49516. };
  49517. /**
  49518. * Creates a line mesh.
  49519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49520. * 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.
  49521. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49522. * The parameter `points` is an array successive Vector3.
  49523. * 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
  49524. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49525. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49526. * When updating an instance, remember that only point positions can change, not the number of points.
  49527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49528. */
  49529. MeshBuilder.CreateLines = function (name, options, scene) {
  49530. if (scene === void 0) { scene = null; }
  49531. var colors = (options.colors) ? [options.colors] : null;
  49532. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49533. return lines;
  49534. };
  49535. /**
  49536. * Creates a dashed line mesh.
  49537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49538. * 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.
  49539. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49540. * The parameter `points` is an array successive Vector3.
  49541. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49542. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49543. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49544. * 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
  49545. * When updating an instance, remember that only point positions can change, not the number of points.
  49546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49547. */
  49548. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49549. if (scene === void 0) { scene = null; }
  49550. var points = options.points;
  49551. var instance = options.instance;
  49552. var gapSize = options.gapSize || 1;
  49553. var dashSize = options.dashSize || 3;
  49554. if (instance) {
  49555. var positionFunction = function (positions) {
  49556. var curvect = BABYLON.Vector3.Zero();
  49557. var nbSeg = positions.length / 6;
  49558. var lg = 0;
  49559. var nb = 0;
  49560. var shft = 0;
  49561. var dashshft = 0;
  49562. var curshft = 0;
  49563. var p = 0;
  49564. var i = 0;
  49565. var j = 0;
  49566. for (i = 0; i < points.length - 1; i++) {
  49567. points[i + 1].subtractToRef(points[i], curvect);
  49568. lg += curvect.length();
  49569. }
  49570. shft = lg / nbSeg;
  49571. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49572. for (i = 0; i < points.length - 1; i++) {
  49573. points[i + 1].subtractToRef(points[i], curvect);
  49574. nb = Math.floor(curvect.length() / shft);
  49575. curvect.normalize();
  49576. j = 0;
  49577. while (j < nb && p < positions.length) {
  49578. curshft = shft * j;
  49579. positions[p] = points[i].x + curshft * curvect.x;
  49580. positions[p + 1] = points[i].y + curshft * curvect.y;
  49581. positions[p + 2] = points[i].z + curshft * curvect.z;
  49582. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49583. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49584. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49585. p += 6;
  49586. j++;
  49587. }
  49588. }
  49589. while (p < positions.length) {
  49590. positions[p] = points[i].x;
  49591. positions[p + 1] = points[i].y;
  49592. positions[p + 2] = points[i].z;
  49593. p += 3;
  49594. }
  49595. };
  49596. instance.updateMeshPositions(positionFunction, false);
  49597. return instance;
  49598. }
  49599. // dashed lines creation
  49600. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49601. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49602. vertexData.applyToMesh(dashedLines, options.updatable);
  49603. dashedLines.dashSize = dashSize;
  49604. dashedLines.gapSize = gapSize;
  49605. return dashedLines;
  49606. };
  49607. /**
  49608. * Creates an extruded shape mesh.
  49609. * 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.
  49610. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49611. *
  49612. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49613. * 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
  49614. * extruded along the Z axis.
  49615. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49616. * 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.
  49617. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49618. * 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
  49619. * 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
  49620. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49621. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49622. * 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).
  49623. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49624. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49626. */
  49627. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49628. if (scene === void 0) { scene = null; }
  49629. var path = options.path;
  49630. var shape = options.shape;
  49631. var scale = options.scale || 1;
  49632. var rotation = options.rotation || 0;
  49633. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49634. var updatable = options.updatable;
  49635. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49636. var instance = options.instance || null;
  49637. var invertUV = options.invertUV || false;
  49638. 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);
  49639. };
  49640. /**
  49641. * Creates an custom extruded shape mesh.
  49642. * 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.
  49643. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49644. *
  49645. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49646. * 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
  49647. * extruded along the Z axis.
  49648. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49649. * 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
  49650. * and the distance of this point from the begining of the path :
  49651. * ```javascript
  49652. * var rotationFunction = function(i, distance) {
  49653. * // do things
  49654. * return rotationValue; }
  49655. * ```
  49656. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49657. * 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
  49658. * and the distance of this point from the begining of the path :
  49659. * ```javascript
  49660. * var scaleFunction = function(i, distance) {
  49661. * // do things
  49662. * return scaleValue;}
  49663. * ```
  49664. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49665. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49666. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49667. * 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
  49668. * 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
  49669. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49671. * 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).
  49672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49673. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49674. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49675. */
  49676. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49677. var path = options.path;
  49678. var shape = options.shape;
  49679. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49680. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49681. var ribbonCloseArray = options.ribbonCloseArray || false;
  49682. var ribbonClosePath = options.ribbonClosePath || false;
  49683. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49684. var updatable = options.updatable;
  49685. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49686. var instance = options.instance;
  49687. var invertUV = options.invertUV || false;
  49688. 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);
  49689. };
  49690. /**
  49691. * Creates lathe mesh.
  49692. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49693. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49694. *
  49695. * 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
  49696. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49697. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49698. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49699. * 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.
  49700. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49701. * 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
  49702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49703. * 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).
  49704. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49705. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49707. */
  49708. MeshBuilder.CreateLathe = function (name, options, scene) {
  49709. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49710. var closed = (options.closed === undefined) ? true : options.closed;
  49711. var shape = options.shape;
  49712. var radius = options.radius || 1;
  49713. var tessellation = options.tessellation || 64;
  49714. var updatable = options.updatable;
  49715. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49716. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49717. var pi2 = Math.PI * 2;
  49718. var paths = new Array();
  49719. var invertUV = options.invertUV || false;
  49720. var i = 0;
  49721. var p = 0;
  49722. var step = pi2 / tessellation * arc;
  49723. var rotated;
  49724. var path = new Array();
  49725. ;
  49726. for (i = 0; i <= tessellation; i++) {
  49727. var path = [];
  49728. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49729. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49730. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49731. }
  49732. for (p = 0; p < shape.length; p++) {
  49733. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49734. path.push(rotated);
  49735. }
  49736. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49737. 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));
  49738. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49739. }
  49740. paths.push(path);
  49741. }
  49742. // lathe ribbon
  49743. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49744. return lathe;
  49745. };
  49746. /**
  49747. * Creates a plane mesh.
  49748. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49749. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49750. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49751. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49753. * 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).
  49754. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49756. */
  49757. MeshBuilder.CreatePlane = function (name, options, scene) {
  49758. var plane = new BABYLON.Mesh(name, scene);
  49759. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49760. plane._originalBuilderSideOrientation = options.sideOrientation;
  49761. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49762. vertexData.applyToMesh(plane, options.updatable);
  49763. if (options.sourcePlane) {
  49764. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49765. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49766. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49767. plane.rotate(vectorProduct, product);
  49768. }
  49769. return plane;
  49770. };
  49771. /**
  49772. * Creates a ground mesh.
  49773. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49774. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49775. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49777. */
  49778. MeshBuilder.CreateGround = function (name, options, scene) {
  49779. var ground = new BABYLON.GroundMesh(name, scene);
  49780. ground._setReady(false);
  49781. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49782. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49783. ground._width = options.width || 1;
  49784. ground._height = options.height || 1;
  49785. ground._maxX = ground._width / 2;
  49786. ground._maxZ = ground._height / 2;
  49787. ground._minX = -ground._maxX;
  49788. ground._minZ = -ground._maxZ;
  49789. var vertexData = BABYLON.VertexData.CreateGround(options);
  49790. vertexData.applyToMesh(ground, options.updatable);
  49791. ground._setReady(true);
  49792. return ground;
  49793. };
  49794. /**
  49795. * Creates a tiled ground mesh.
  49796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49797. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49798. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49799. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49800. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49801. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49802. * numbers of subdivisions on the ground width and height of each tile.
  49803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49804. */
  49805. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49806. var tiledGround = new BABYLON.Mesh(name, scene);
  49807. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49808. vertexData.applyToMesh(tiledGround, options.updatable);
  49809. return tiledGround;
  49810. };
  49811. /**
  49812. * Creates a ground mesh from a height map.
  49813. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49815. * The parameter `url` sets the URL of the height map image resource.
  49816. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49817. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49818. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49819. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49820. * 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.
  49821. * 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).
  49822. * This function is passed the newly built mesh :
  49823. * ```javascript
  49824. * function(mesh) { // do things
  49825. * return; }
  49826. * ```
  49827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49828. */
  49829. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49830. var width = options.width || 10.0;
  49831. var height = options.height || 10.0;
  49832. var subdivisions = options.subdivisions || 1 | 0;
  49833. var minHeight = options.minHeight || 0.0;
  49834. var maxHeight = options.maxHeight || 1.0;
  49835. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49836. var updatable = options.updatable;
  49837. var onReady = options.onReady;
  49838. var ground = new BABYLON.GroundMesh(name, scene);
  49839. ground._subdivisionsX = subdivisions;
  49840. ground._subdivisionsY = subdivisions;
  49841. ground._width = width;
  49842. ground._height = height;
  49843. ground._maxX = ground._width / 2.0;
  49844. ground._maxZ = ground._height / 2.0;
  49845. ground._minX = -ground._maxX;
  49846. ground._minZ = -ground._maxZ;
  49847. ground._setReady(false);
  49848. var onload = function (img) {
  49849. // Getting height map data
  49850. var canvas = document.createElement("canvas");
  49851. var context = canvas.getContext("2d");
  49852. if (!context) {
  49853. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49854. }
  49855. if (scene.isDisposed) {
  49856. return;
  49857. }
  49858. var bufferWidth = img.width;
  49859. var bufferHeight = img.height;
  49860. canvas.width = bufferWidth;
  49861. canvas.height = bufferHeight;
  49862. context.drawImage(img, 0, 0);
  49863. // Create VertexData from map data
  49864. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49865. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49866. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49867. width: width, height: height,
  49868. subdivisions: subdivisions,
  49869. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49870. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49871. });
  49872. vertexData.applyToMesh(ground, updatable);
  49873. ground._setReady(true);
  49874. //execute ready callback, if set
  49875. if (onReady) {
  49876. onReady(ground);
  49877. }
  49878. };
  49879. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  49880. return ground;
  49881. };
  49882. /**
  49883. * Creates a polygon mesh.
  49884. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  49885. * 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.
  49886. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49888. * 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).
  49889. * Remember you can only change the shape positions, not their number when updating a polygon.
  49890. */
  49891. MeshBuilder.CreatePolygon = function (name, options, scene) {
  49892. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49893. var shape = options.shape;
  49894. var holes = options.holes || [];
  49895. var depth = options.depth || 0;
  49896. var contours = [];
  49897. var hole = [];
  49898. for (var i = 0; i < shape.length; i++) {
  49899. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  49900. }
  49901. var epsilon = 0.00000001;
  49902. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  49903. contours.pop();
  49904. }
  49905. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  49906. for (var hNb = 0; hNb < holes.length; hNb++) {
  49907. hole = [];
  49908. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  49909. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  49910. }
  49911. polygonTriangulation.addHole(hole);
  49912. }
  49913. var polygon = polygonTriangulation.build(options.updatable, depth);
  49914. polygon._originalBuilderSideOrientation = options.sideOrientation;
  49915. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  49916. vertexData.applyToMesh(polygon, options.updatable);
  49917. return polygon;
  49918. };
  49919. ;
  49920. /**
  49921. * Creates an extruded polygon mesh, with depth in the Y direction.
  49922. * 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).
  49923. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49924. */
  49925. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  49926. return MeshBuilder.CreatePolygon(name, options, scene);
  49927. };
  49928. ;
  49929. /**
  49930. * Creates a tube mesh.
  49931. * 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.
  49932. *
  49933. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  49934. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  49935. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  49936. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  49937. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  49938. * 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.
  49939. * It must return a radius value (positive float) :
  49940. * ```javascript
  49941. * var radiusFunction = function(i, distance) {
  49942. * // do things
  49943. * return radius; }
  49944. * ```
  49945. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  49946. * 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
  49947. * 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
  49948. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49949. * 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).
  49950. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49951. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49953. */
  49954. MeshBuilder.CreateTube = function (name, options, scene) {
  49955. var path = options.path;
  49956. var instance = options.instance;
  49957. var radius = 1.0;
  49958. if (instance) {
  49959. radius = instance.radius;
  49960. }
  49961. if (options.radius !== undefined) {
  49962. radius = options.radius;
  49963. }
  49964. ;
  49965. var tessellation = options.tessellation || 64 | 0;
  49966. var radiusFunction = options.radiusFunction || null;
  49967. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49968. var invertUV = options.invertUV || false;
  49969. var updatable = options.updatable;
  49970. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49971. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  49972. // tube geometry
  49973. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  49974. var tangents = path3D.getTangents();
  49975. var normals = path3D.getNormals();
  49976. var distances = path3D.getDistances();
  49977. var pi2 = Math.PI * 2;
  49978. var step = pi2 / tessellation * arc;
  49979. var returnRadius = function () { return radius; };
  49980. var radiusFunctionFinal = radiusFunction || returnRadius;
  49981. var circlePath;
  49982. var rad;
  49983. var normal;
  49984. var rotated;
  49985. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49986. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49987. for (var i = 0; i < path.length; i++) {
  49988. rad = radiusFunctionFinal(i, distances[i]); // current radius
  49989. circlePath = Array(); // current circle array
  49990. normal = normals[i]; // current normal
  49991. for (var t = 0; t < tessellation; t++) {
  49992. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  49993. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  49994. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  49995. rotated.scaleInPlace(rad).addInPlace(path[i]);
  49996. circlePath[t] = rotated;
  49997. }
  49998. circlePaths[index] = circlePath;
  49999. index++;
  50000. }
  50001. // cap
  50002. var capPath = function (nbPoints, pathIndex) {
  50003. var pointCap = Array();
  50004. for (var i = 0; i < nbPoints; i++) {
  50005. pointCap.push(path[pathIndex]);
  50006. }
  50007. return pointCap;
  50008. };
  50009. switch (cap) {
  50010. case BABYLON.Mesh.NO_CAP:
  50011. break;
  50012. case BABYLON.Mesh.CAP_START:
  50013. circlePaths[0] = capPath(tessellation, 0);
  50014. circlePaths[1] = circlePaths[2].slice(0);
  50015. break;
  50016. case BABYLON.Mesh.CAP_END:
  50017. circlePaths[index] = circlePaths[index - 1].slice(0);
  50018. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50019. break;
  50020. case BABYLON.Mesh.CAP_ALL:
  50021. circlePaths[0] = capPath(tessellation, 0);
  50022. circlePaths[1] = circlePaths[2].slice(0);
  50023. circlePaths[index] = circlePaths[index - 1].slice(0);
  50024. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50025. break;
  50026. default:
  50027. break;
  50028. }
  50029. return circlePaths;
  50030. };
  50031. var path3D;
  50032. var pathArray;
  50033. if (instance) {
  50034. var arc = options.arc || instance.arc;
  50035. path3D = (instance.path3D).update(path);
  50036. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50037. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50038. instance.path3D = path3D;
  50039. instance.pathArray = pathArray;
  50040. instance.arc = arc;
  50041. instance.radius = radius;
  50042. return instance;
  50043. }
  50044. // tube creation
  50045. path3D = new BABYLON.Path3D(path);
  50046. var newPathArray = new Array();
  50047. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50048. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50049. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50050. tube.pathArray = pathArray;
  50051. tube.path3D = path3D;
  50052. tube.tessellation = tessellation;
  50053. tube.cap = cap;
  50054. tube.arc = options.arc;
  50055. tube.radius = radius;
  50056. return tube;
  50057. };
  50058. /**
  50059. * Creates a polyhedron mesh.
  50060. *
  50061. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50062. * 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
  50063. * to choose the wanted type.
  50064. * The parameter `size` (positive float, default 1) sets the polygon size.
  50065. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50066. * 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`.
  50067. * 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
  50068. * 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)`).
  50069. * 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
  50070. * 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.
  50071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50072. * 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).
  50073. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50075. */
  50076. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50077. var polyhedron = new BABYLON.Mesh(name, scene);
  50078. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50079. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50080. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50081. vertexData.applyToMesh(polyhedron, options.updatable);
  50082. return polyhedron;
  50083. };
  50084. /**
  50085. * Creates a decal mesh.
  50086. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50087. * 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.
  50088. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50089. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50090. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50091. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50092. */
  50093. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50094. var indices = sourceMesh.getIndices();
  50095. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50096. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50097. var position = options.position || BABYLON.Vector3.Zero();
  50098. var normal = options.normal || BABYLON.Vector3.Up();
  50099. var size = options.size || BABYLON.Vector3.One();
  50100. var angle = options.angle || 0;
  50101. // Getting correct rotation
  50102. if (!normal) {
  50103. var target = new BABYLON.Vector3(0, 0, 1);
  50104. var camera = sourceMesh.getScene().activeCamera;
  50105. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50106. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50107. }
  50108. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50109. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50110. var pitch = Math.atan2(normal.y, len);
  50111. // Matrix
  50112. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50113. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50114. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50115. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50116. var vertexData = new BABYLON.VertexData();
  50117. vertexData.indices = [];
  50118. vertexData.positions = [];
  50119. vertexData.normals = [];
  50120. vertexData.uvs = [];
  50121. var currentVertexDataIndex = 0;
  50122. var extractDecalVector3 = function (indexId) {
  50123. var result = new BABYLON.PositionNormalVertex();
  50124. if (!indices || !positions || !normals) {
  50125. return result;
  50126. }
  50127. var vertexId = indices[indexId];
  50128. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50129. // Send vector to decal local world
  50130. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50131. // Get normal
  50132. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50133. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50134. return result;
  50135. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50136. var clip = function (vertices, axis) {
  50137. if (vertices.length === 0) {
  50138. return vertices;
  50139. }
  50140. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50141. var clipVertices = function (v0, v1) {
  50142. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50143. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50144. };
  50145. var result = new Array();
  50146. for (var index = 0; index < vertices.length; index += 3) {
  50147. var v1Out;
  50148. var v2Out;
  50149. var v3Out;
  50150. var total = 0;
  50151. var nV1 = null;
  50152. var nV2 = null;
  50153. var nV3 = null;
  50154. var nV4 = null;
  50155. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50156. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50157. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50158. v1Out = d1 > 0;
  50159. v2Out = d2 > 0;
  50160. v3Out = d3 > 0;
  50161. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50162. switch (total) {
  50163. case 0:
  50164. result.push(vertices[index]);
  50165. result.push(vertices[index + 1]);
  50166. result.push(vertices[index + 2]);
  50167. break;
  50168. case 1:
  50169. if (v1Out) {
  50170. nV1 = vertices[index + 1];
  50171. nV2 = vertices[index + 2];
  50172. nV3 = clipVertices(vertices[index], nV1);
  50173. nV4 = clipVertices(vertices[index], nV2);
  50174. }
  50175. if (v2Out) {
  50176. nV1 = vertices[index];
  50177. nV2 = vertices[index + 2];
  50178. nV3 = clipVertices(vertices[index + 1], nV1);
  50179. nV4 = clipVertices(vertices[index + 1], nV2);
  50180. result.push(nV3);
  50181. result.push(nV2.clone());
  50182. result.push(nV1.clone());
  50183. result.push(nV2.clone());
  50184. result.push(nV3.clone());
  50185. result.push(nV4);
  50186. break;
  50187. }
  50188. if (v3Out) {
  50189. nV1 = vertices[index];
  50190. nV2 = vertices[index + 1];
  50191. nV3 = clipVertices(vertices[index + 2], nV1);
  50192. nV4 = clipVertices(vertices[index + 2], nV2);
  50193. }
  50194. if (nV1 && nV2 && nV3 && nV4) {
  50195. result.push(nV1.clone());
  50196. result.push(nV2.clone());
  50197. result.push(nV3);
  50198. result.push(nV4);
  50199. result.push(nV3.clone());
  50200. result.push(nV2.clone());
  50201. }
  50202. break;
  50203. case 2:
  50204. if (!v1Out) {
  50205. nV1 = vertices[index].clone();
  50206. nV2 = clipVertices(nV1, vertices[index + 1]);
  50207. nV3 = clipVertices(nV1, vertices[index + 2]);
  50208. result.push(nV1);
  50209. result.push(nV2);
  50210. result.push(nV3);
  50211. }
  50212. if (!v2Out) {
  50213. nV1 = vertices[index + 1].clone();
  50214. nV2 = clipVertices(nV1, vertices[index + 2]);
  50215. nV3 = clipVertices(nV1, vertices[index]);
  50216. result.push(nV1);
  50217. result.push(nV2);
  50218. result.push(nV3);
  50219. }
  50220. if (!v3Out) {
  50221. nV1 = vertices[index + 2].clone();
  50222. nV2 = clipVertices(nV1, vertices[index]);
  50223. nV3 = clipVertices(nV1, vertices[index + 1]);
  50224. result.push(nV1);
  50225. result.push(nV2);
  50226. result.push(nV3);
  50227. }
  50228. break;
  50229. case 3:
  50230. break;
  50231. }
  50232. }
  50233. return result;
  50234. };
  50235. for (var index = 0; index < indices.length; index += 3) {
  50236. var faceVertices = new Array();
  50237. faceVertices.push(extractDecalVector3(index));
  50238. faceVertices.push(extractDecalVector3(index + 1));
  50239. faceVertices.push(extractDecalVector3(index + 2));
  50240. // Clip
  50241. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50242. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50243. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50244. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50245. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50246. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50247. if (faceVertices.length === 0) {
  50248. continue;
  50249. }
  50250. // Add UVs and get back to world
  50251. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50252. var vertex = faceVertices[vIndex];
  50253. //TODO check for Int32Array | Uint32Array | Uint16Array
  50254. vertexData.indices.push(currentVertexDataIndex);
  50255. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50256. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50257. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50258. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50259. currentVertexDataIndex++;
  50260. }
  50261. }
  50262. // Return mesh
  50263. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50264. vertexData.applyToMesh(decal);
  50265. decal.position = position.clone();
  50266. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50267. return decal;
  50268. };
  50269. // Privates
  50270. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50271. // extrusion geometry
  50272. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50273. var tangents = path3D.getTangents();
  50274. var normals = path3D.getNormals();
  50275. var binormals = path3D.getBinormals();
  50276. var distances = path3D.getDistances();
  50277. var angle = 0;
  50278. var returnScale = function () { return scale !== null ? scale : 1; };
  50279. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50280. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50281. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50282. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50283. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50284. for (var i = 0; i < curve.length; i++) {
  50285. var shapePath = new Array();
  50286. var angleStep = rotate(i, distances[i]);
  50287. var scaleRatio = scl(i, distances[i]);
  50288. for (var p = 0; p < shape.length; p++) {
  50289. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50290. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50291. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50292. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50293. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50294. shapePath[p] = rotated;
  50295. }
  50296. shapePaths[index] = shapePath;
  50297. angle += angleStep;
  50298. index++;
  50299. }
  50300. // cap
  50301. var capPath = function (shapePath) {
  50302. var pointCap = Array();
  50303. var barycenter = BABYLON.Vector3.Zero();
  50304. var i;
  50305. for (i = 0; i < shapePath.length; i++) {
  50306. barycenter.addInPlace(shapePath[i]);
  50307. }
  50308. barycenter.scaleInPlace(1.0 / shapePath.length);
  50309. for (i = 0; i < shapePath.length; i++) {
  50310. pointCap.push(barycenter);
  50311. }
  50312. return pointCap;
  50313. };
  50314. switch (cap) {
  50315. case BABYLON.Mesh.NO_CAP:
  50316. break;
  50317. case BABYLON.Mesh.CAP_START:
  50318. shapePaths[0] = capPath(shapePaths[2]);
  50319. shapePaths[1] = shapePaths[2];
  50320. break;
  50321. case BABYLON.Mesh.CAP_END:
  50322. shapePaths[index] = shapePaths[index - 1];
  50323. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50324. break;
  50325. case BABYLON.Mesh.CAP_ALL:
  50326. shapePaths[0] = capPath(shapePaths[2]);
  50327. shapePaths[1] = shapePaths[2];
  50328. shapePaths[index] = shapePaths[index - 1];
  50329. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50330. break;
  50331. default:
  50332. break;
  50333. }
  50334. return shapePaths;
  50335. };
  50336. var path3D;
  50337. var pathArray;
  50338. if (instance) {
  50339. path3D = (instance.path3D).update(curve);
  50340. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50341. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50342. return instance;
  50343. }
  50344. // extruded shape creation
  50345. path3D = new BABYLON.Path3D(curve);
  50346. var newShapePaths = new Array();
  50347. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50348. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50349. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50350. extrudedGeneric.pathArray = pathArray;
  50351. extrudedGeneric.path3D = path3D;
  50352. extrudedGeneric.cap = cap;
  50353. return extrudedGeneric;
  50354. };
  50355. return MeshBuilder;
  50356. }());
  50357. BABYLON.MeshBuilder = MeshBuilder;
  50358. })(BABYLON || (BABYLON = {}));
  50359. //# sourceMappingURL=babylon.meshBuilder.js.map
  50360. var BABYLON;
  50361. (function (BABYLON) {
  50362. var AudioEngine = /** @class */ (function () {
  50363. function AudioEngine() {
  50364. this._audioContext = null;
  50365. this._audioContextInitialized = false;
  50366. this.canUseWebAudio = false;
  50367. this.WarnedWebAudioUnsupported = false;
  50368. this.unlocked = false;
  50369. this.isMP3supported = false;
  50370. this.isOGGsupported = false;
  50371. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50372. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50373. this.canUseWebAudio = true;
  50374. }
  50375. var audioElem = document.createElement('audio');
  50376. try {
  50377. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50378. this.isMP3supported = true;
  50379. }
  50380. }
  50381. catch (e) {
  50382. // protect error during capability check.
  50383. }
  50384. try {
  50385. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50386. this.isOGGsupported = true;
  50387. }
  50388. }
  50389. catch (e) {
  50390. // protect error during capability check.
  50391. }
  50392. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50393. this._unlockiOSaudio();
  50394. }
  50395. else {
  50396. this.unlocked = true;
  50397. }
  50398. }
  50399. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50400. get: function () {
  50401. if (!this._audioContextInitialized) {
  50402. this._initializeAudioContext();
  50403. }
  50404. return this._audioContext;
  50405. },
  50406. enumerable: true,
  50407. configurable: true
  50408. });
  50409. AudioEngine.prototype._unlockiOSaudio = function () {
  50410. var _this = this;
  50411. var unlockaudio = function () {
  50412. if (!_this.audioContext) {
  50413. return;
  50414. }
  50415. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50416. var source = _this.audioContext.createBufferSource();
  50417. source.buffer = buffer;
  50418. source.connect(_this.audioContext.destination);
  50419. source.start(0);
  50420. setTimeout(function () {
  50421. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50422. _this.unlocked = true;
  50423. window.removeEventListener('touchend', unlockaudio, false);
  50424. if (_this.onAudioUnlocked) {
  50425. _this.onAudioUnlocked();
  50426. }
  50427. }
  50428. }, 0);
  50429. };
  50430. window.addEventListener('touchend', unlockaudio, false);
  50431. };
  50432. AudioEngine.prototype._initializeAudioContext = function () {
  50433. try {
  50434. if (this.canUseWebAudio) {
  50435. this._audioContext = new AudioContext();
  50436. // create a global volume gain node
  50437. this.masterGain = this._audioContext.createGain();
  50438. this.masterGain.gain.value = 1;
  50439. this.masterGain.connect(this._audioContext.destination);
  50440. this._audioContextInitialized = true;
  50441. }
  50442. }
  50443. catch (e) {
  50444. this.canUseWebAudio = false;
  50445. BABYLON.Tools.Error("Web Audio: " + e.message);
  50446. }
  50447. };
  50448. AudioEngine.prototype.dispose = function () {
  50449. if (this.canUseWebAudio && this._audioContextInitialized) {
  50450. if (this._connectedAnalyser && this._audioContext) {
  50451. this._connectedAnalyser.stopDebugCanvas();
  50452. this._connectedAnalyser.dispose();
  50453. this.masterGain.disconnect();
  50454. this.masterGain.connect(this._audioContext.destination);
  50455. this._connectedAnalyser = null;
  50456. }
  50457. this.masterGain.gain.value = 1;
  50458. }
  50459. this.WarnedWebAudioUnsupported = false;
  50460. };
  50461. AudioEngine.prototype.getGlobalVolume = function () {
  50462. if (this.canUseWebAudio && this._audioContextInitialized) {
  50463. return this.masterGain.gain.value;
  50464. }
  50465. else {
  50466. return -1;
  50467. }
  50468. };
  50469. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50470. if (this.canUseWebAudio && this._audioContextInitialized) {
  50471. this.masterGain.gain.value = newVolume;
  50472. }
  50473. };
  50474. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50475. if (this._connectedAnalyser) {
  50476. this._connectedAnalyser.stopDebugCanvas();
  50477. }
  50478. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50479. this._connectedAnalyser = analyser;
  50480. this.masterGain.disconnect();
  50481. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50482. }
  50483. };
  50484. return AudioEngine;
  50485. }());
  50486. BABYLON.AudioEngine = AudioEngine;
  50487. })(BABYLON || (BABYLON = {}));
  50488. //# sourceMappingURL=babylon.audioEngine.js.map
  50489. var BABYLON;
  50490. (function (BABYLON) {
  50491. var Sound = /** @class */ (function () {
  50492. /**
  50493. * Create a sound and attach it to a scene
  50494. * @param name Name of your sound
  50495. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50496. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50497. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50498. */
  50499. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50500. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50501. var _this = this;
  50502. this.autoplay = false;
  50503. this.loop = false;
  50504. this.useCustomAttenuation = false;
  50505. this.spatialSound = false;
  50506. this.refDistance = 1;
  50507. this.rolloffFactor = 1;
  50508. this.maxDistance = 100;
  50509. this.distanceModel = "linear";
  50510. this._panningModel = "equalpower";
  50511. this._playbackRate = 1;
  50512. this._streaming = false;
  50513. this._startTime = 0;
  50514. this._startOffset = 0;
  50515. this._position = BABYLON.Vector3.Zero();
  50516. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50517. this._volume = 1;
  50518. this._isReadyToPlay = false;
  50519. this.isPlaying = false;
  50520. this.isPaused = false;
  50521. this._isDirectional = false;
  50522. // Used if you'd like to create a directional sound.
  50523. // If not set, the sound will be omnidirectional
  50524. this._coneInnerAngle = 360;
  50525. this._coneOuterAngle = 360;
  50526. this._coneOuterGain = 0;
  50527. this._isOutputConnected = false;
  50528. this._urlType = "Unknown";
  50529. this.name = name;
  50530. this._scene = scene;
  50531. this._readyToPlayCallback = readyToPlayCallback;
  50532. // Default custom attenuation function is a linear attenuation
  50533. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50534. if (currentDistance < maxDistance) {
  50535. return currentVolume * (1 - currentDistance / maxDistance);
  50536. }
  50537. else {
  50538. return 0;
  50539. }
  50540. };
  50541. if (options) {
  50542. this.autoplay = options.autoplay || false;
  50543. this.loop = options.loop || false;
  50544. // if volume === 0, we need another way to check this option
  50545. if (options.volume !== undefined) {
  50546. this._volume = options.volume;
  50547. }
  50548. this.spatialSound = options.spatialSound || false;
  50549. this.maxDistance = options.maxDistance || 100;
  50550. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50551. this.rolloffFactor = options.rolloffFactor || 1;
  50552. this.refDistance = options.refDistance || 1;
  50553. this.distanceModel = options.distanceModel || "linear";
  50554. this._playbackRate = options.playbackRate || 1;
  50555. this._streaming = options.streaming || false;
  50556. }
  50557. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50558. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50559. this._soundGain.gain.value = this._volume;
  50560. this._inputAudioNode = this._soundGain;
  50561. this._ouputAudioNode = this._soundGain;
  50562. if (this.spatialSound) {
  50563. this._createSpatialParameters();
  50564. }
  50565. this._scene.mainSoundTrack.AddSound(this);
  50566. var validParameter = true;
  50567. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50568. if (urlOrArrayBuffer) {
  50569. if (typeof (urlOrArrayBuffer) === "string")
  50570. this._urlType = "String";
  50571. if (Array.isArray(urlOrArrayBuffer))
  50572. this._urlType = "Array";
  50573. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50574. this._urlType = "ArrayBuffer";
  50575. var urls = [];
  50576. var codecSupportedFound = false;
  50577. switch (this._urlType) {
  50578. case "ArrayBuffer":
  50579. if (urlOrArrayBuffer.byteLength > 0) {
  50580. codecSupportedFound = true;
  50581. this._soundLoaded(urlOrArrayBuffer);
  50582. }
  50583. break;
  50584. case "String":
  50585. urls.push(urlOrArrayBuffer);
  50586. case "Array":
  50587. if (urls.length === 0)
  50588. urls = urlOrArrayBuffer;
  50589. // If we found a supported format, we load it immediately and stop the loop
  50590. for (var i = 0; i < urls.length; i++) {
  50591. var url = urls[i];
  50592. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50593. codecSupportedFound = true;
  50594. }
  50595. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50596. codecSupportedFound = true;
  50597. }
  50598. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50599. codecSupportedFound = true;
  50600. }
  50601. if (url.indexOf("blob:") !== -1) {
  50602. codecSupportedFound = true;
  50603. }
  50604. if (codecSupportedFound) {
  50605. // Loading sound using XHR2
  50606. if (!this._streaming) {
  50607. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50608. }
  50609. else {
  50610. this._htmlAudioElement = new Audio(url);
  50611. this._htmlAudioElement.controls = false;
  50612. this._htmlAudioElement.loop = this.loop;
  50613. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50614. this._htmlAudioElement.preload = "auto";
  50615. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50616. _this._isReadyToPlay = true;
  50617. if (_this.autoplay) {
  50618. _this.play();
  50619. }
  50620. if (_this._readyToPlayCallback) {
  50621. _this._readyToPlayCallback();
  50622. }
  50623. });
  50624. document.body.appendChild(this._htmlAudioElement);
  50625. }
  50626. break;
  50627. }
  50628. }
  50629. break;
  50630. default:
  50631. validParameter = false;
  50632. break;
  50633. }
  50634. if (!validParameter) {
  50635. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50636. }
  50637. else {
  50638. if (!codecSupportedFound) {
  50639. this._isReadyToPlay = true;
  50640. // Simulating a ready to play event to avoid breaking code path
  50641. if (this._readyToPlayCallback) {
  50642. window.setTimeout(function () {
  50643. if (_this._readyToPlayCallback) {
  50644. _this._readyToPlayCallback();
  50645. }
  50646. }, 1000);
  50647. }
  50648. }
  50649. }
  50650. }
  50651. }
  50652. else {
  50653. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50654. this._scene.mainSoundTrack.AddSound(this);
  50655. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50656. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50657. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50658. }
  50659. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50660. if (this._readyToPlayCallback) {
  50661. window.setTimeout(function () {
  50662. if (_this._readyToPlayCallback) {
  50663. _this._readyToPlayCallback();
  50664. }
  50665. }, 1000);
  50666. }
  50667. }
  50668. }
  50669. Sound.prototype.dispose = function () {
  50670. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50671. if (this.isPlaying) {
  50672. this.stop();
  50673. }
  50674. this._isReadyToPlay = false;
  50675. if (this.soundTrackId === -1) {
  50676. this._scene.mainSoundTrack.RemoveSound(this);
  50677. }
  50678. else {
  50679. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50680. }
  50681. if (this._soundGain) {
  50682. this._soundGain.disconnect();
  50683. this._soundGain = null;
  50684. }
  50685. if (this._soundPanner) {
  50686. this._soundPanner.disconnect();
  50687. this._soundPanner = null;
  50688. }
  50689. if (this._soundSource) {
  50690. this._soundSource.disconnect();
  50691. this._soundSource = null;
  50692. }
  50693. this._audioBuffer = null;
  50694. if (this._htmlAudioElement) {
  50695. this._htmlAudioElement.pause();
  50696. this._htmlAudioElement.src = "";
  50697. document.body.removeChild(this._htmlAudioElement);
  50698. }
  50699. if (this._connectedMesh && this._registerFunc) {
  50700. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50701. this._connectedMesh = null;
  50702. }
  50703. }
  50704. };
  50705. Sound.prototype.isReady = function () {
  50706. return this._isReadyToPlay;
  50707. };
  50708. Sound.prototype._soundLoaded = function (audioData) {
  50709. var _this = this;
  50710. if (!BABYLON.Engine.audioEngine.audioContext) {
  50711. return;
  50712. }
  50713. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50714. _this._audioBuffer = buffer;
  50715. _this._isReadyToPlay = true;
  50716. if (_this.autoplay) {
  50717. _this.play();
  50718. }
  50719. if (_this._readyToPlayCallback) {
  50720. _this._readyToPlayCallback();
  50721. }
  50722. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50723. };
  50724. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50725. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50726. this._audioBuffer = audioBuffer;
  50727. this._isReadyToPlay = true;
  50728. }
  50729. };
  50730. Sound.prototype.updateOptions = function (options) {
  50731. if (options) {
  50732. this.loop = options.loop || this.loop;
  50733. this.maxDistance = options.maxDistance || this.maxDistance;
  50734. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50735. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50736. this.refDistance = options.refDistance || this.refDistance;
  50737. this.distanceModel = options.distanceModel || this.distanceModel;
  50738. this._playbackRate = options.playbackRate || this._playbackRate;
  50739. this._updateSpatialParameters();
  50740. if (this.isPlaying) {
  50741. if (this._streaming) {
  50742. this._htmlAudioElement.playbackRate = this._playbackRate;
  50743. }
  50744. else {
  50745. if (this._soundSource) {
  50746. this._soundSource.playbackRate.value = this._playbackRate;
  50747. }
  50748. }
  50749. }
  50750. }
  50751. };
  50752. Sound.prototype._createSpatialParameters = function () {
  50753. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50754. if (this._scene.headphone) {
  50755. this._panningModel = "HRTF";
  50756. }
  50757. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50758. this._updateSpatialParameters();
  50759. this._soundPanner.connect(this._ouputAudioNode);
  50760. this._inputAudioNode = this._soundPanner;
  50761. }
  50762. };
  50763. Sound.prototype._updateSpatialParameters = function () {
  50764. if (this.spatialSound && this._soundPanner) {
  50765. if (this.useCustomAttenuation) {
  50766. // Tricks to disable in a way embedded Web Audio attenuation
  50767. this._soundPanner.distanceModel = "linear";
  50768. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50769. this._soundPanner.refDistance = 1;
  50770. this._soundPanner.rolloffFactor = 1;
  50771. this._soundPanner.panningModel = this._panningModel;
  50772. }
  50773. else {
  50774. this._soundPanner.distanceModel = this.distanceModel;
  50775. this._soundPanner.maxDistance = this.maxDistance;
  50776. this._soundPanner.refDistance = this.refDistance;
  50777. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50778. this._soundPanner.panningModel = this._panningModel;
  50779. }
  50780. }
  50781. };
  50782. Sound.prototype.switchPanningModelToHRTF = function () {
  50783. this._panningModel = "HRTF";
  50784. this._switchPanningModel();
  50785. };
  50786. Sound.prototype.switchPanningModelToEqualPower = function () {
  50787. this._panningModel = "equalpower";
  50788. this._switchPanningModel();
  50789. };
  50790. Sound.prototype._switchPanningModel = function () {
  50791. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50792. this._soundPanner.panningModel = this._panningModel;
  50793. }
  50794. };
  50795. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50796. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50797. if (this._isOutputConnected) {
  50798. this._ouputAudioNode.disconnect();
  50799. }
  50800. this._ouputAudioNode.connect(soundTrackAudioNode);
  50801. this._isOutputConnected = true;
  50802. }
  50803. };
  50804. /**
  50805. * Transform this sound into a directional source
  50806. * @param coneInnerAngle Size of the inner cone in degree
  50807. * @param coneOuterAngle Size of the outer cone in degree
  50808. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50809. */
  50810. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50811. if (coneOuterAngle < coneInnerAngle) {
  50812. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50813. return;
  50814. }
  50815. this._coneInnerAngle = coneInnerAngle;
  50816. this._coneOuterAngle = coneOuterAngle;
  50817. this._coneOuterGain = coneOuterGain;
  50818. this._isDirectional = true;
  50819. if (this.isPlaying && this.loop) {
  50820. this.stop();
  50821. this.play();
  50822. }
  50823. };
  50824. Sound.prototype.setPosition = function (newPosition) {
  50825. this._position = newPosition;
  50826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50827. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50828. }
  50829. };
  50830. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50831. this._localDirection = newLocalDirection;
  50832. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50833. this._updateDirection();
  50834. }
  50835. };
  50836. Sound.prototype._updateDirection = function () {
  50837. if (!this._connectedMesh || !this._soundPanner) {
  50838. return;
  50839. }
  50840. var mat = this._connectedMesh.getWorldMatrix();
  50841. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50842. direction.normalize();
  50843. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50844. };
  50845. Sound.prototype.updateDistanceFromListener = function () {
  50846. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50847. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50848. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50849. }
  50850. };
  50851. Sound.prototype.setAttenuationFunction = function (callback) {
  50852. this._customAttenuationFunction = callback;
  50853. };
  50854. /**
  50855. * Play the sound
  50856. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50857. * @param offset (optional) Start the sound setting it at a specific time
  50858. */
  50859. Sound.prototype.play = function (time, offset) {
  50860. var _this = this;
  50861. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50862. try {
  50863. if (this._startOffset < 0) {
  50864. time = -this._startOffset;
  50865. this._startOffset = 0;
  50866. }
  50867. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50868. if (!this._soundSource || !this._streamingSource) {
  50869. if (this.spatialSound && this._soundPanner) {
  50870. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50871. if (this._isDirectional) {
  50872. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50873. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50874. this._soundPanner.coneOuterGain = this._coneOuterGain;
  50875. if (this._connectedMesh) {
  50876. this._updateDirection();
  50877. }
  50878. else {
  50879. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  50880. }
  50881. }
  50882. }
  50883. }
  50884. if (this._streaming) {
  50885. if (!this._streamingSource) {
  50886. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  50887. this._htmlAudioElement.onended = function () { _this._onended(); };
  50888. this._htmlAudioElement.playbackRate = this._playbackRate;
  50889. }
  50890. this._streamingSource.disconnect();
  50891. this._streamingSource.connect(this._inputAudioNode);
  50892. this._htmlAudioElement.play();
  50893. }
  50894. else {
  50895. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  50896. this._soundSource.buffer = this._audioBuffer;
  50897. this._soundSource.connect(this._inputAudioNode);
  50898. this._soundSource.loop = this.loop;
  50899. this._soundSource.playbackRate.value = this._playbackRate;
  50900. this._soundSource.onended = function () { _this._onended(); };
  50901. if (this._soundSource.buffer) {
  50902. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  50903. }
  50904. }
  50905. this._startTime = startTime;
  50906. this.isPlaying = true;
  50907. this.isPaused = false;
  50908. }
  50909. catch (ex) {
  50910. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  50911. }
  50912. }
  50913. };
  50914. Sound.prototype._onended = function () {
  50915. this.isPlaying = false;
  50916. if (this.onended) {
  50917. this.onended();
  50918. }
  50919. };
  50920. /**
  50921. * Stop the sound
  50922. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  50923. */
  50924. Sound.prototype.stop = function (time) {
  50925. if (this.isPlaying) {
  50926. if (this._streaming) {
  50927. this._htmlAudioElement.pause();
  50928. // Test needed for Firefox or it will generate an Invalid State Error
  50929. if (this._htmlAudioElement.currentTime > 0) {
  50930. this._htmlAudioElement.currentTime = 0;
  50931. }
  50932. }
  50933. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  50934. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50935. this._soundSource.stop(stopTime);
  50936. this._soundSource.onended = function () { };
  50937. if (!this.isPaused) {
  50938. this._startOffset = 0;
  50939. }
  50940. }
  50941. this.isPlaying = false;
  50942. }
  50943. };
  50944. Sound.prototype.pause = function () {
  50945. if (this.isPlaying) {
  50946. this.isPaused = true;
  50947. if (this._streaming) {
  50948. this._htmlAudioElement.pause();
  50949. }
  50950. else if (BABYLON.Engine.audioEngine.audioContext) {
  50951. this.stop(0);
  50952. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  50953. }
  50954. }
  50955. };
  50956. Sound.prototype.setVolume = function (newVolume, time) {
  50957. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  50958. if (time && BABYLON.Engine.audioEngine.audioContext) {
  50959. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  50960. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  50961. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  50962. }
  50963. else {
  50964. this._soundGain.gain.value = newVolume;
  50965. }
  50966. }
  50967. this._volume = newVolume;
  50968. };
  50969. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  50970. this._playbackRate = newPlaybackRate;
  50971. if (this.isPlaying) {
  50972. if (this._streaming) {
  50973. this._htmlAudioElement.playbackRate = this._playbackRate;
  50974. }
  50975. else if (this._soundSource) {
  50976. this._soundSource.playbackRate.value = this._playbackRate;
  50977. }
  50978. }
  50979. };
  50980. Sound.prototype.getVolume = function () {
  50981. return this._volume;
  50982. };
  50983. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  50984. var _this = this;
  50985. if (this._connectedMesh && this._registerFunc) {
  50986. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50987. this._registerFunc = null;
  50988. }
  50989. this._connectedMesh = meshToConnectTo;
  50990. if (!this.spatialSound) {
  50991. this.spatialSound = true;
  50992. this._createSpatialParameters();
  50993. if (this.isPlaying && this.loop) {
  50994. this.stop();
  50995. this.play();
  50996. }
  50997. }
  50998. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  50999. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51000. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51001. };
  51002. Sound.prototype.detachFromMesh = function () {
  51003. if (this._connectedMesh && this._registerFunc) {
  51004. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51005. this._registerFunc = null;
  51006. this._connectedMesh = null;
  51007. }
  51008. };
  51009. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51010. if (!node.getBoundingInfo) {
  51011. return;
  51012. }
  51013. var mesh = node;
  51014. var boundingInfo = mesh.getBoundingInfo();
  51015. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51016. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51017. this._updateDirection();
  51018. }
  51019. };
  51020. Sound.prototype.clone = function () {
  51021. var _this = this;
  51022. if (!this._streaming) {
  51023. var setBufferAndRun = function () {
  51024. if (_this._isReadyToPlay) {
  51025. clonedSound._audioBuffer = _this.getAudioBuffer();
  51026. clonedSound._isReadyToPlay = true;
  51027. if (clonedSound.autoplay) {
  51028. clonedSound.play();
  51029. }
  51030. }
  51031. else {
  51032. window.setTimeout(setBufferAndRun, 300);
  51033. }
  51034. };
  51035. var currentOptions = {
  51036. autoplay: this.autoplay, loop: this.loop,
  51037. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51038. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51039. refDistance: this.refDistance, distanceModel: this.distanceModel
  51040. };
  51041. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51042. if (this.useCustomAttenuation) {
  51043. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51044. }
  51045. clonedSound.setPosition(this._position);
  51046. clonedSound.setPlaybackRate(this._playbackRate);
  51047. setBufferAndRun();
  51048. return clonedSound;
  51049. }
  51050. else {
  51051. return null;
  51052. }
  51053. };
  51054. Sound.prototype.getAudioBuffer = function () {
  51055. return this._audioBuffer;
  51056. };
  51057. Sound.prototype.serialize = function () {
  51058. var serializationObject = {
  51059. name: this.name,
  51060. url: this.name,
  51061. autoplay: this.autoplay,
  51062. loop: this.loop,
  51063. volume: this._volume,
  51064. spatialSound: this.spatialSound,
  51065. maxDistance: this.maxDistance,
  51066. rolloffFactor: this.rolloffFactor,
  51067. refDistance: this.refDistance,
  51068. distanceModel: this.distanceModel,
  51069. playbackRate: this._playbackRate,
  51070. panningModel: this._panningModel,
  51071. soundTrackId: this.soundTrackId
  51072. };
  51073. if (this.spatialSound) {
  51074. if (this._connectedMesh)
  51075. serializationObject.connectedMeshId = this._connectedMesh.id;
  51076. serializationObject.position = this._position.asArray();
  51077. serializationObject.refDistance = this.refDistance;
  51078. serializationObject.distanceModel = this.distanceModel;
  51079. serializationObject.isDirectional = this._isDirectional;
  51080. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51081. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51082. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51083. serializationObject.coneOuterGain = this._coneOuterGain;
  51084. }
  51085. return serializationObject;
  51086. };
  51087. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51088. var soundName = parsedSound.name;
  51089. var soundUrl;
  51090. if (parsedSound.url) {
  51091. soundUrl = rootUrl + parsedSound.url;
  51092. }
  51093. else {
  51094. soundUrl = rootUrl + soundName;
  51095. }
  51096. var options = {
  51097. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51098. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51099. rolloffFactor: parsedSound.rolloffFactor,
  51100. refDistance: parsedSound.refDistance,
  51101. distanceModel: parsedSound.distanceModel,
  51102. playbackRate: parsedSound.playbackRate
  51103. };
  51104. var newSound;
  51105. if (!sourceSound) {
  51106. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51107. scene._addPendingData(newSound);
  51108. }
  51109. else {
  51110. var setBufferAndRun = function () {
  51111. if (sourceSound._isReadyToPlay) {
  51112. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51113. newSound._isReadyToPlay = true;
  51114. if (newSound.autoplay) {
  51115. newSound.play();
  51116. }
  51117. }
  51118. else {
  51119. window.setTimeout(setBufferAndRun, 300);
  51120. }
  51121. };
  51122. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51123. setBufferAndRun();
  51124. }
  51125. if (parsedSound.position) {
  51126. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51127. newSound.setPosition(soundPosition);
  51128. }
  51129. if (parsedSound.isDirectional) {
  51130. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51131. if (parsedSound.localDirectionToMesh) {
  51132. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51133. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51134. }
  51135. }
  51136. if (parsedSound.connectedMeshId) {
  51137. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51138. if (connectedMesh) {
  51139. newSound.attachToMesh(connectedMesh);
  51140. }
  51141. }
  51142. return newSound;
  51143. };
  51144. return Sound;
  51145. }());
  51146. BABYLON.Sound = Sound;
  51147. })(BABYLON || (BABYLON = {}));
  51148. //# sourceMappingURL=babylon.sound.js.map
  51149. var BABYLON;
  51150. (function (BABYLON) {
  51151. var SoundTrack = /** @class */ (function () {
  51152. function SoundTrack(scene, options) {
  51153. this.id = -1;
  51154. this._isMainTrack = false;
  51155. this._isInitialized = false;
  51156. this._scene = scene;
  51157. this.soundCollection = new Array();
  51158. this._options = options;
  51159. if (!this._isMainTrack) {
  51160. this._scene.soundTracks.push(this);
  51161. this.id = this._scene.soundTracks.length - 1;
  51162. }
  51163. }
  51164. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51165. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51166. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51167. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51168. if (this._options) {
  51169. if (this._options.volume) {
  51170. this._outputAudioNode.gain.value = this._options.volume;
  51171. }
  51172. if (this._options.mainTrack) {
  51173. this._isMainTrack = this._options.mainTrack;
  51174. }
  51175. }
  51176. this._isInitialized = true;
  51177. }
  51178. };
  51179. SoundTrack.prototype.dispose = function () {
  51180. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51181. if (this._connectedAnalyser) {
  51182. this._connectedAnalyser.stopDebugCanvas();
  51183. }
  51184. while (this.soundCollection.length) {
  51185. this.soundCollection[0].dispose();
  51186. }
  51187. if (this._outputAudioNode) {
  51188. this._outputAudioNode.disconnect();
  51189. }
  51190. this._outputAudioNode = null;
  51191. }
  51192. };
  51193. SoundTrack.prototype.AddSound = function (sound) {
  51194. if (!this._isInitialized) {
  51195. this._initializeSoundTrackAudioGraph();
  51196. }
  51197. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51198. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51199. }
  51200. if (sound.soundTrackId) {
  51201. if (sound.soundTrackId === -1) {
  51202. this._scene.mainSoundTrack.RemoveSound(sound);
  51203. }
  51204. else {
  51205. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51206. }
  51207. }
  51208. this.soundCollection.push(sound);
  51209. sound.soundTrackId = this.id;
  51210. };
  51211. SoundTrack.prototype.RemoveSound = function (sound) {
  51212. var index = this.soundCollection.indexOf(sound);
  51213. if (index !== -1) {
  51214. this.soundCollection.splice(index, 1);
  51215. }
  51216. };
  51217. SoundTrack.prototype.setVolume = function (newVolume) {
  51218. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51219. this._outputAudioNode.gain.value = newVolume;
  51220. }
  51221. };
  51222. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51223. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51224. for (var i = 0; i < this.soundCollection.length; i++) {
  51225. this.soundCollection[i].switchPanningModelToHRTF();
  51226. }
  51227. }
  51228. };
  51229. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51230. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51231. for (var i = 0; i < this.soundCollection.length; i++) {
  51232. this.soundCollection[i].switchPanningModelToEqualPower();
  51233. }
  51234. }
  51235. };
  51236. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51237. if (this._connectedAnalyser) {
  51238. this._connectedAnalyser.stopDebugCanvas();
  51239. }
  51240. this._connectedAnalyser = analyser;
  51241. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51242. this._outputAudioNode.disconnect();
  51243. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51244. }
  51245. };
  51246. return SoundTrack;
  51247. }());
  51248. BABYLON.SoundTrack = SoundTrack;
  51249. })(BABYLON || (BABYLON = {}));
  51250. //# sourceMappingURL=babylon.soundtrack.js.map
  51251. var BABYLON;
  51252. (function (BABYLON) {
  51253. var Analyser = /** @class */ (function () {
  51254. function Analyser(scene) {
  51255. this.SMOOTHING = 0.75;
  51256. this.FFT_SIZE = 512;
  51257. this.BARGRAPHAMPLITUDE = 256;
  51258. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51259. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51260. this._scene = scene;
  51261. this._audioEngine = BABYLON.Engine.audioEngine;
  51262. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51263. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51264. this._webAudioAnalyser.minDecibels = -140;
  51265. this._webAudioAnalyser.maxDecibels = 0;
  51266. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51267. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51268. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51269. }
  51270. }
  51271. Analyser.prototype.getFrequencyBinCount = function () {
  51272. if (this._audioEngine.canUseWebAudio) {
  51273. return this._webAudioAnalyser.frequencyBinCount;
  51274. }
  51275. else {
  51276. return 0;
  51277. }
  51278. };
  51279. Analyser.prototype.getByteFrequencyData = function () {
  51280. if (this._audioEngine.canUseWebAudio) {
  51281. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51282. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51283. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51284. }
  51285. return this._byteFreqs;
  51286. };
  51287. Analyser.prototype.getByteTimeDomainData = function () {
  51288. if (this._audioEngine.canUseWebAudio) {
  51289. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51290. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51291. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51292. }
  51293. return this._byteTime;
  51294. };
  51295. Analyser.prototype.getFloatFrequencyData = function () {
  51296. if (this._audioEngine.canUseWebAudio) {
  51297. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51298. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51299. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51300. }
  51301. return this._floatFreqs;
  51302. };
  51303. Analyser.prototype.drawDebugCanvas = function () {
  51304. var _this = this;
  51305. if (this._audioEngine.canUseWebAudio) {
  51306. if (!this._debugCanvas) {
  51307. this._debugCanvas = document.createElement("canvas");
  51308. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51309. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51310. this._debugCanvas.style.position = "absolute";
  51311. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51312. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51313. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51314. document.body.appendChild(this._debugCanvas);
  51315. this._registerFunc = function () {
  51316. _this.drawDebugCanvas();
  51317. };
  51318. this._scene.registerBeforeRender(this._registerFunc);
  51319. }
  51320. if (this._registerFunc && this._debugCanvasContext) {
  51321. var workingArray = this.getByteFrequencyData();
  51322. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51323. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51324. // Draw the frequency domain chart.
  51325. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51326. var value = workingArray[i];
  51327. var percent = value / this.BARGRAPHAMPLITUDE;
  51328. var height = this.DEBUGCANVASSIZE.height * percent;
  51329. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51330. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51331. var hue = i / this.getFrequencyBinCount() * 360;
  51332. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51333. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51334. }
  51335. }
  51336. }
  51337. };
  51338. Analyser.prototype.stopDebugCanvas = function () {
  51339. if (this._debugCanvas) {
  51340. if (this._registerFunc) {
  51341. this._scene.unregisterBeforeRender(this._registerFunc);
  51342. this._registerFunc = null;
  51343. }
  51344. document.body.removeChild(this._debugCanvas);
  51345. this._debugCanvas = null;
  51346. this._debugCanvasContext = null;
  51347. }
  51348. };
  51349. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51350. if (this._audioEngine.canUseWebAudio) {
  51351. inputAudioNode.connect(this._webAudioAnalyser);
  51352. this._webAudioAnalyser.connect(outputAudioNode);
  51353. }
  51354. };
  51355. Analyser.prototype.dispose = function () {
  51356. if (this._audioEngine.canUseWebAudio) {
  51357. this._webAudioAnalyser.disconnect();
  51358. }
  51359. };
  51360. return Analyser;
  51361. }());
  51362. BABYLON.Analyser = Analyser;
  51363. })(BABYLON || (BABYLON = {}));
  51364. //# sourceMappingURL=babylon.analyser.js.map
  51365. var BABYLON;
  51366. (function (BABYLON) {
  51367. var CubeTexture = /** @class */ (function (_super) {
  51368. __extends(CubeTexture, _super);
  51369. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51370. if (extensions === void 0) { extensions = null; }
  51371. if (noMipmap === void 0) { noMipmap = false; }
  51372. if (files === void 0) { files = null; }
  51373. if (onLoad === void 0) { onLoad = null; }
  51374. if (onError === void 0) { onError = null; }
  51375. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51376. if (prefiltered === void 0) { prefiltered = false; }
  51377. if (forcedExtension === void 0) { forcedExtension = null; }
  51378. var _this = _super.call(this, scene) || this;
  51379. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51380. _this.name = rootUrl;
  51381. _this.url = rootUrl;
  51382. _this._noMipmap = noMipmap;
  51383. _this.hasAlpha = false;
  51384. _this._format = format;
  51385. _this._prefiltered = prefiltered;
  51386. _this.isCube = true;
  51387. _this._textureMatrix = BABYLON.Matrix.Identity();
  51388. if (prefiltered) {
  51389. _this.gammaSpace = false;
  51390. }
  51391. if (!rootUrl && !files) {
  51392. return _this;
  51393. }
  51394. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51395. var lastDot = rootUrl.lastIndexOf(".");
  51396. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51397. var isDDS = (extension === ".dds");
  51398. if (!files) {
  51399. if (!isDDS && !extensions) {
  51400. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51401. }
  51402. files = [];
  51403. if (extensions) {
  51404. for (var index = 0; index < extensions.length; index++) {
  51405. files.push(rootUrl + extensions[index]);
  51406. }
  51407. }
  51408. }
  51409. _this._files = files;
  51410. if (!_this._texture) {
  51411. if (!scene.useDelayedTextureLoading) {
  51412. if (prefiltered) {
  51413. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51414. }
  51415. else {
  51416. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51417. }
  51418. }
  51419. else {
  51420. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51421. }
  51422. }
  51423. else if (onLoad) {
  51424. if (_this._texture.isReady) {
  51425. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51426. }
  51427. else {
  51428. _this._texture.onLoadedObservable.add(onLoad);
  51429. }
  51430. }
  51431. return _this;
  51432. }
  51433. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51434. return new CubeTexture("", scene, null, noMipmap, files);
  51435. };
  51436. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51437. if (forcedExtension === void 0) { forcedExtension = null; }
  51438. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51439. };
  51440. // Methods
  51441. CubeTexture.prototype.delayLoad = function () {
  51442. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51443. return;
  51444. }
  51445. var scene = this.getScene();
  51446. if (!scene) {
  51447. return;
  51448. }
  51449. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51450. this._texture = this._getFromCache(this.url, this._noMipmap);
  51451. if (!this._texture) {
  51452. if (this._prefiltered) {
  51453. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51454. }
  51455. else {
  51456. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51457. }
  51458. }
  51459. };
  51460. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51461. return this._textureMatrix;
  51462. };
  51463. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51464. this._textureMatrix = value;
  51465. };
  51466. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51467. var texture = BABYLON.SerializationHelper.Parse(function () {
  51468. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51469. }, parsedTexture, scene);
  51470. // Animations
  51471. if (parsedTexture.animations) {
  51472. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51473. var parsedAnimation = parsedTexture.animations[animationIndex];
  51474. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51475. }
  51476. }
  51477. return texture;
  51478. };
  51479. CubeTexture.prototype.clone = function () {
  51480. var _this = this;
  51481. return BABYLON.SerializationHelper.Clone(function () {
  51482. var scene = _this.getScene();
  51483. if (!scene) {
  51484. return _this;
  51485. }
  51486. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51487. }, this);
  51488. };
  51489. return CubeTexture;
  51490. }(BABYLON.BaseTexture));
  51491. BABYLON.CubeTexture = CubeTexture;
  51492. })(BABYLON || (BABYLON = {}));
  51493. //# sourceMappingURL=babylon.cubeTexture.js.map
  51494. var BABYLON;
  51495. (function (BABYLON) {
  51496. var RenderTargetTexture = /** @class */ (function (_super) {
  51497. __extends(RenderTargetTexture, _super);
  51498. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51499. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51500. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51501. if (isCube === void 0) { isCube = false; }
  51502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51503. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51504. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51505. if (isMulti === void 0) { isMulti = false; }
  51506. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51507. _this.isCube = isCube;
  51508. /**
  51509. * Use this list to define the list of mesh you want to render.
  51510. */
  51511. _this.renderList = new Array();
  51512. _this.renderParticles = true;
  51513. _this.renderSprites = false;
  51514. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51515. _this.ignoreCameraViewport = false;
  51516. // Events
  51517. /**
  51518. * An event triggered when the texture is unbind.
  51519. * @type {BABYLON.Observable}
  51520. */
  51521. _this.onBeforeBindObservable = new BABYLON.Observable();
  51522. /**
  51523. * An event triggered when the texture is unbind.
  51524. * @type {BABYLON.Observable}
  51525. */
  51526. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51527. /**
  51528. * An event triggered before rendering the texture
  51529. * @type {BABYLON.Observable}
  51530. */
  51531. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51532. /**
  51533. * An event triggered after rendering the texture
  51534. * @type {BABYLON.Observable}
  51535. */
  51536. _this.onAfterRenderObservable = new BABYLON.Observable();
  51537. /**
  51538. * An event triggered after the texture clear
  51539. * @type {BABYLON.Observable}
  51540. */
  51541. _this.onClearObservable = new BABYLON.Observable();
  51542. _this._currentRefreshId = -1;
  51543. _this._refreshRate = 1;
  51544. _this._samples = 1;
  51545. scene = _this.getScene();
  51546. if (!scene) {
  51547. return _this;
  51548. }
  51549. _this._engine = scene.getEngine();
  51550. _this.name = name;
  51551. _this.isRenderTarget = true;
  51552. _this._initialSizeParameter = size;
  51553. _this._processSizeParameter(size);
  51554. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51555. });
  51556. _this._generateMipMaps = generateMipMaps ? true : false;
  51557. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51558. // Rendering groups
  51559. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51560. if (isMulti) {
  51561. return _this;
  51562. }
  51563. _this._renderTargetOptions = {
  51564. generateMipMaps: generateMipMaps,
  51565. type: type,
  51566. samplingMode: samplingMode,
  51567. generateDepthBuffer: generateDepthBuffer,
  51568. generateStencilBuffer: generateStencilBuffer
  51569. };
  51570. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51571. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51572. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51573. }
  51574. if (isCube) {
  51575. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51576. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51577. _this._textureMatrix = BABYLON.Matrix.Identity();
  51578. }
  51579. else {
  51580. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51581. }
  51582. return _this;
  51583. }
  51584. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51585. get: function () {
  51586. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51587. },
  51588. enumerable: true,
  51589. configurable: true
  51590. });
  51591. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51592. get: function () {
  51593. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51594. },
  51595. enumerable: true,
  51596. configurable: true
  51597. });
  51598. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51599. get: function () {
  51600. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51601. },
  51602. enumerable: true,
  51603. configurable: true
  51604. });
  51605. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51606. set: function (callback) {
  51607. if (this._onAfterUnbindObserver) {
  51608. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51609. }
  51610. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51611. },
  51612. enumerable: true,
  51613. configurable: true
  51614. });
  51615. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51616. set: function (callback) {
  51617. if (this._onBeforeRenderObserver) {
  51618. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51619. }
  51620. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51621. },
  51622. enumerable: true,
  51623. configurable: true
  51624. });
  51625. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51626. set: function (callback) {
  51627. if (this._onAfterRenderObserver) {
  51628. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51629. }
  51630. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51631. },
  51632. enumerable: true,
  51633. configurable: true
  51634. });
  51635. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51636. set: function (callback) {
  51637. if (this._onClearObserver) {
  51638. this.onClearObservable.remove(this._onClearObserver);
  51639. }
  51640. this._onClearObserver = this.onClearObservable.add(callback);
  51641. },
  51642. enumerable: true,
  51643. configurable: true
  51644. });
  51645. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51646. get: function () {
  51647. return this._renderTargetOptions;
  51648. },
  51649. enumerable: true,
  51650. configurable: true
  51651. });
  51652. RenderTargetTexture.prototype._onRatioRescale = function () {
  51653. if (this._sizeRatio) {
  51654. this.resize(this._initialSizeParameter);
  51655. }
  51656. };
  51657. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51658. if (size.ratio) {
  51659. this._sizeRatio = size.ratio;
  51660. this._size = {
  51661. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51662. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51663. };
  51664. }
  51665. else {
  51666. this._size = size;
  51667. }
  51668. };
  51669. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51670. get: function () {
  51671. return this._samples;
  51672. },
  51673. set: function (value) {
  51674. if (this._samples === value) {
  51675. return;
  51676. }
  51677. var scene = this.getScene();
  51678. if (!scene) {
  51679. return;
  51680. }
  51681. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51682. },
  51683. enumerable: true,
  51684. configurable: true
  51685. });
  51686. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51687. this._currentRefreshId = -1;
  51688. };
  51689. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51690. get: function () {
  51691. return this._refreshRate;
  51692. },
  51693. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51694. set: function (value) {
  51695. this._refreshRate = value;
  51696. this.resetRefreshCounter();
  51697. },
  51698. enumerable: true,
  51699. configurable: true
  51700. });
  51701. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51702. if (!this._postProcessManager) {
  51703. var scene = this.getScene();
  51704. if (!scene) {
  51705. return;
  51706. }
  51707. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51708. this._postProcesses = new Array();
  51709. }
  51710. this._postProcesses.push(postProcess);
  51711. this._postProcesses[0].autoClear = false;
  51712. };
  51713. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51714. if (!this._postProcesses) {
  51715. return;
  51716. }
  51717. if (dispose) {
  51718. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51719. var postProcess = _a[_i];
  51720. postProcess.dispose();
  51721. }
  51722. }
  51723. this._postProcesses = [];
  51724. };
  51725. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51726. if (!this._postProcesses) {
  51727. return;
  51728. }
  51729. var index = this._postProcesses.indexOf(postProcess);
  51730. if (index === -1) {
  51731. return;
  51732. }
  51733. this._postProcesses.splice(index, 1);
  51734. if (this._postProcesses.length > 0) {
  51735. this._postProcesses[0].autoClear = false;
  51736. }
  51737. };
  51738. RenderTargetTexture.prototype._shouldRender = function () {
  51739. if (this._currentRefreshId === -1) {
  51740. this._currentRefreshId = 1;
  51741. return true;
  51742. }
  51743. if (this.refreshRate === this._currentRefreshId) {
  51744. this._currentRefreshId = 1;
  51745. return true;
  51746. }
  51747. this._currentRefreshId++;
  51748. return false;
  51749. };
  51750. RenderTargetTexture.prototype.getRenderSize = function () {
  51751. if (this._size.width) {
  51752. return this._size.width;
  51753. }
  51754. return this._size;
  51755. };
  51756. RenderTargetTexture.prototype.getRenderWidth = function () {
  51757. if (this._size.width) {
  51758. return this._size.width;
  51759. }
  51760. return this._size;
  51761. };
  51762. RenderTargetTexture.prototype.getRenderHeight = function () {
  51763. if (this._size.width) {
  51764. return this._size.height;
  51765. }
  51766. return this._size;
  51767. };
  51768. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51769. get: function () {
  51770. return true;
  51771. },
  51772. enumerable: true,
  51773. configurable: true
  51774. });
  51775. RenderTargetTexture.prototype.scale = function (ratio) {
  51776. var newSize = this.getRenderSize() * ratio;
  51777. this.resize(newSize);
  51778. };
  51779. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51780. if (this.isCube) {
  51781. return this._textureMatrix;
  51782. }
  51783. return _super.prototype.getReflectionTextureMatrix.call(this);
  51784. };
  51785. RenderTargetTexture.prototype.resize = function (size) {
  51786. this.releaseInternalTexture();
  51787. var scene = this.getScene();
  51788. if (!scene) {
  51789. return;
  51790. }
  51791. this._processSizeParameter(size);
  51792. if (this.isCube) {
  51793. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51794. }
  51795. else {
  51796. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51797. }
  51798. };
  51799. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51800. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51801. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51802. var scene = this.getScene();
  51803. if (!scene) {
  51804. return;
  51805. }
  51806. var engine = scene.getEngine();
  51807. if (this.useCameraPostProcesses !== undefined) {
  51808. useCameraPostProcess = this.useCameraPostProcesses;
  51809. }
  51810. if (this._waitingRenderList) {
  51811. this.renderList = [];
  51812. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51813. var id = this._waitingRenderList[index];
  51814. var mesh_1 = scene.getMeshByID(id);
  51815. if (mesh_1) {
  51816. this.renderList.push(mesh_1);
  51817. }
  51818. }
  51819. delete this._waitingRenderList;
  51820. }
  51821. // Is predicate defined?
  51822. if (this.renderListPredicate) {
  51823. if (this.renderList) {
  51824. this.renderList.splice(0); // Clear previous renderList
  51825. }
  51826. else {
  51827. this.renderList = [];
  51828. }
  51829. var scene = this.getScene();
  51830. if (!scene) {
  51831. return;
  51832. }
  51833. var sceneMeshes = scene.meshes;
  51834. for (var index = 0; index < sceneMeshes.length; index++) {
  51835. var mesh = sceneMeshes[index];
  51836. if (this.renderListPredicate(mesh)) {
  51837. this.renderList.push(mesh);
  51838. }
  51839. }
  51840. }
  51841. this.onBeforeBindObservable.notifyObservers(this);
  51842. // Set custom projection.
  51843. // Needs to be before binding to prevent changing the aspect ratio.
  51844. var camera;
  51845. if (this.activeCamera) {
  51846. camera = this.activeCamera;
  51847. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51848. if (this.activeCamera !== scene.activeCamera) {
  51849. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51850. }
  51851. }
  51852. else {
  51853. camera = scene.activeCamera;
  51854. if (camera) {
  51855. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51856. }
  51857. }
  51858. // Prepare renderingManager
  51859. this._renderingManager.reset();
  51860. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51861. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51862. var sceneRenderId = scene.getRenderId();
  51863. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51864. var mesh = currentRenderList[meshIndex];
  51865. if (mesh) {
  51866. if (!mesh.isReady()) {
  51867. // Reset _currentRefreshId
  51868. this.resetRefreshCounter();
  51869. continue;
  51870. }
  51871. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51872. var isMasked = void 0;
  51873. if (!this.renderList && camera) {
  51874. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  51875. }
  51876. else {
  51877. isMasked = false;
  51878. }
  51879. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  51880. mesh._activate(sceneRenderId);
  51881. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51882. var subMesh = mesh.subMeshes[subIndex];
  51883. scene._activeIndices.addCount(subMesh.indexCount, false);
  51884. this._renderingManager.dispatch(subMesh, mesh);
  51885. }
  51886. }
  51887. }
  51888. }
  51889. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  51890. var particleSystem = scene.particleSystems[particleIndex];
  51891. var emitter = particleSystem.emitter;
  51892. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  51893. continue;
  51894. }
  51895. if (currentRenderList.indexOf(emitter) >= 0) {
  51896. this._renderingManager.dispatchParticles(particleSystem);
  51897. }
  51898. }
  51899. if (this.isCube) {
  51900. for (var face = 0; face < 6; face++) {
  51901. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51902. scene.incrementRenderId();
  51903. scene.resetCachedMaterial();
  51904. }
  51905. }
  51906. else {
  51907. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51908. }
  51909. this.onAfterUnbindObservable.notifyObservers(this);
  51910. if (scene.activeCamera) {
  51911. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  51912. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  51913. }
  51914. engine.setViewport(scene.activeCamera.viewport);
  51915. }
  51916. scene.resetCachedMaterial();
  51917. };
  51918. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  51919. var minimum = 128;
  51920. var x = renderDimension * scale;
  51921. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  51922. // Ensure we don't exceed the render dimension (while staying POT)
  51923. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  51924. };
  51925. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  51926. var _this = this;
  51927. if (!this._texture) {
  51928. return;
  51929. }
  51930. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  51931. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51932. });
  51933. };
  51934. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  51935. var scene = this.getScene();
  51936. if (!scene) {
  51937. return;
  51938. }
  51939. var engine = scene.getEngine();
  51940. if (!this._texture) {
  51941. return;
  51942. }
  51943. // Bind
  51944. if (this._postProcessManager) {
  51945. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  51946. }
  51947. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  51948. if (this._texture) {
  51949. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  51950. }
  51951. }
  51952. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  51953. // Clear
  51954. if (this.onClearObservable.hasObservers()) {
  51955. this.onClearObservable.notifyObservers(engine);
  51956. }
  51957. else {
  51958. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  51959. }
  51960. if (!this._doNotChangeAspectRatio) {
  51961. scene.updateTransformMatrix(true);
  51962. }
  51963. // Render
  51964. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  51965. if (this._postProcessManager) {
  51966. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  51967. }
  51968. else if (useCameraPostProcess) {
  51969. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  51970. }
  51971. if (!this._doNotChangeAspectRatio) {
  51972. scene.updateTransformMatrix(true);
  51973. }
  51974. // Dump ?
  51975. if (dumpForDebug) {
  51976. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  51977. }
  51978. // Unbind
  51979. if (!this.isCube || faceIndex === 5) {
  51980. if (this.isCube) {
  51981. if (faceIndex === 5) {
  51982. engine.generateMipMapsForCubemap(this._texture);
  51983. }
  51984. }
  51985. this.unbindFrameBuffer(engine, faceIndex);
  51986. }
  51987. else {
  51988. this.onAfterRenderObservable.notifyObservers(faceIndex);
  51989. }
  51990. };
  51991. /**
  51992. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  51993. * This allowed control for front to back rendering or reversly depending of the special needs.
  51994. *
  51995. * @param renderingGroupId The rendering group id corresponding to its index
  51996. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  51997. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  51998. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  51999. */
  52000. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52001. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52002. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52003. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52004. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52005. };
  52006. /**
  52007. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52008. *
  52009. * @param renderingGroupId The rendering group id corresponding to its index
  52010. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52011. */
  52012. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52013. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52014. };
  52015. RenderTargetTexture.prototype.clone = function () {
  52016. var textureSize = this.getSize();
  52017. 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);
  52018. // Base texture
  52019. newTexture.hasAlpha = this.hasAlpha;
  52020. newTexture.level = this.level;
  52021. // RenderTarget Texture
  52022. newTexture.coordinatesMode = this.coordinatesMode;
  52023. if (this.renderList) {
  52024. newTexture.renderList = this.renderList.slice(0);
  52025. }
  52026. return newTexture;
  52027. };
  52028. RenderTargetTexture.prototype.serialize = function () {
  52029. if (!this.name) {
  52030. return null;
  52031. }
  52032. var serializationObject = _super.prototype.serialize.call(this);
  52033. serializationObject.renderTargetSize = this.getRenderSize();
  52034. serializationObject.renderList = [];
  52035. if (this.renderList) {
  52036. for (var index = 0; index < this.renderList.length; index++) {
  52037. serializationObject.renderList.push(this.renderList[index].id);
  52038. }
  52039. }
  52040. return serializationObject;
  52041. };
  52042. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52043. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52044. var objBuffer = this.getInternalTexture();
  52045. var scene = this.getScene();
  52046. if (objBuffer && scene) {
  52047. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52048. }
  52049. };
  52050. RenderTargetTexture.prototype.dispose = function () {
  52051. if (this._postProcessManager) {
  52052. this._postProcessManager.dispose();
  52053. this._postProcessManager = null;
  52054. }
  52055. this.clearPostProcesses(true);
  52056. if (this._resizeObserver) {
  52057. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52058. this._resizeObserver = null;
  52059. }
  52060. this.renderList = null;
  52061. // Remove from custom render targets
  52062. var scene = this.getScene();
  52063. if (!scene) {
  52064. return;
  52065. }
  52066. var index = scene.customRenderTargets.indexOf(this);
  52067. if (index >= 0) {
  52068. scene.customRenderTargets.splice(index, 1);
  52069. }
  52070. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52071. var camera = _a[_i];
  52072. index = camera.customRenderTargets.indexOf(this);
  52073. if (index >= 0) {
  52074. camera.customRenderTargets.splice(index, 1);
  52075. }
  52076. }
  52077. _super.prototype.dispose.call(this);
  52078. };
  52079. RenderTargetTexture.prototype._rebuild = function () {
  52080. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52081. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52082. }
  52083. if (this._postProcessManager) {
  52084. this._postProcessManager._rebuild();
  52085. }
  52086. };
  52087. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52088. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52089. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52090. return RenderTargetTexture;
  52091. }(BABYLON.Texture));
  52092. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52093. })(BABYLON || (BABYLON = {}));
  52094. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52095. var BABYLON;
  52096. (function (BABYLON) {
  52097. ;
  52098. var MultiRenderTarget = /** @class */ (function (_super) {
  52099. __extends(MultiRenderTarget, _super);
  52100. function MultiRenderTarget(name, size, count, scene, options) {
  52101. var _this = this;
  52102. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52103. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52104. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52105. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52106. _this._engine = scene.getEngine();
  52107. if (!_this.isSupported) {
  52108. _this.dispose();
  52109. return;
  52110. }
  52111. var types = [];
  52112. var samplingModes = [];
  52113. for (var i = 0; i < count; i++) {
  52114. if (options && options.types && options.types[i] !== undefined) {
  52115. types.push(options.types[i]);
  52116. }
  52117. else {
  52118. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52119. }
  52120. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52121. samplingModes.push(options.samplingModes[i]);
  52122. }
  52123. else {
  52124. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52125. }
  52126. }
  52127. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52128. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52129. _this._size = size;
  52130. _this._multiRenderTargetOptions = {
  52131. samplingModes: samplingModes,
  52132. generateMipMaps: generateMipMaps,
  52133. generateDepthBuffer: generateDepthBuffer,
  52134. generateStencilBuffer: generateStencilBuffer,
  52135. generateDepthTexture: generateDepthTexture,
  52136. types: types,
  52137. textureCount: count
  52138. };
  52139. _this._createInternalTextures();
  52140. _this._createTextures();
  52141. return _this;
  52142. }
  52143. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52144. get: function () {
  52145. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52146. },
  52147. enumerable: true,
  52148. configurable: true
  52149. });
  52150. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52151. get: function () {
  52152. return this._textures;
  52153. },
  52154. enumerable: true,
  52155. configurable: true
  52156. });
  52157. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52158. get: function () {
  52159. return this._textures[this._textures.length - 1];
  52160. },
  52161. enumerable: true,
  52162. configurable: true
  52163. });
  52164. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52165. set: function (wrap) {
  52166. if (this._textures) {
  52167. for (var i = 0; i < this._textures.length; i++) {
  52168. this._textures[i].wrapU = wrap;
  52169. }
  52170. }
  52171. },
  52172. enumerable: true,
  52173. configurable: true
  52174. });
  52175. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52176. set: function (wrap) {
  52177. if (this._textures) {
  52178. for (var i = 0; i < this._textures.length; i++) {
  52179. this._textures[i].wrapV = wrap;
  52180. }
  52181. }
  52182. },
  52183. enumerable: true,
  52184. configurable: true
  52185. });
  52186. MultiRenderTarget.prototype._rebuild = function () {
  52187. this.releaseInternalTextures();
  52188. this._createInternalTextures();
  52189. for (var i = 0; i < this._internalTextures.length; i++) {
  52190. var texture = this._textures[i];
  52191. texture._texture = this._internalTextures[i];
  52192. }
  52193. // Keeps references to frame buffer and stencil/depth buffer
  52194. this._texture = this._internalTextures[0];
  52195. };
  52196. MultiRenderTarget.prototype._createInternalTextures = function () {
  52197. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52198. };
  52199. MultiRenderTarget.prototype._createTextures = function () {
  52200. this._textures = [];
  52201. for (var i = 0; i < this._internalTextures.length; i++) {
  52202. var texture = new BABYLON.Texture(null, this.getScene());
  52203. texture._texture = this._internalTextures[i];
  52204. this._textures.push(texture);
  52205. }
  52206. // Keeps references to frame buffer and stencil/depth buffer
  52207. this._texture = this._internalTextures[0];
  52208. };
  52209. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52210. get: function () {
  52211. return this._samples;
  52212. },
  52213. set: function (value) {
  52214. if (this._samples === value) {
  52215. return;
  52216. }
  52217. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52218. },
  52219. enumerable: true,
  52220. configurable: true
  52221. });
  52222. MultiRenderTarget.prototype.resize = function (size) {
  52223. this.releaseInternalTextures();
  52224. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52225. this._createInternalTextures();
  52226. };
  52227. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52228. var _this = this;
  52229. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52230. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52231. });
  52232. };
  52233. MultiRenderTarget.prototype.dispose = function () {
  52234. this.releaseInternalTextures();
  52235. _super.prototype.dispose.call(this);
  52236. };
  52237. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52238. if (!this._internalTextures) {
  52239. return;
  52240. }
  52241. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52242. if (this._internalTextures[i] !== undefined) {
  52243. this._internalTextures[i].dispose();
  52244. this._internalTextures.splice(i, 1);
  52245. }
  52246. }
  52247. };
  52248. return MultiRenderTarget;
  52249. }(BABYLON.RenderTargetTexture));
  52250. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52251. })(BABYLON || (BABYLON = {}));
  52252. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52253. var BABYLON;
  52254. (function (BABYLON) {
  52255. var MirrorTexture = /** @class */ (function (_super) {
  52256. __extends(MirrorTexture, _super);
  52257. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52258. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52260. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52261. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52262. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52263. _this._transformMatrix = BABYLON.Matrix.Zero();
  52264. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52265. _this._adaptiveBlurKernel = 0;
  52266. _this._blurKernelX = 0;
  52267. _this._blurKernelY = 0;
  52268. _this._blurRatio = 1.0;
  52269. _this.ignoreCameraViewport = true;
  52270. _this.onBeforeRenderObservable.add(function () {
  52271. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52272. _this._savedViewMatrix = scene.getViewMatrix();
  52273. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52274. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52275. scene.clipPlane = _this.mirrorPlane;
  52276. scene.getEngine().cullBackFaces = false;
  52277. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52278. });
  52279. _this.onAfterRenderObservable.add(function () {
  52280. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52281. scene.getEngine().cullBackFaces = true;
  52282. scene._mirroredCameraPosition = null;
  52283. delete scene.clipPlane;
  52284. });
  52285. return _this;
  52286. }
  52287. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52288. get: function () {
  52289. return this._blurRatio;
  52290. },
  52291. set: function (value) {
  52292. if (this._blurRatio === value) {
  52293. return;
  52294. }
  52295. this._blurRatio = value;
  52296. this._preparePostProcesses();
  52297. },
  52298. enumerable: true,
  52299. configurable: true
  52300. });
  52301. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52302. set: function (value) {
  52303. this._adaptiveBlurKernel = value;
  52304. this._autoComputeBlurKernel();
  52305. },
  52306. enumerable: true,
  52307. configurable: true
  52308. });
  52309. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52310. set: function (value) {
  52311. this.blurKernelX = value;
  52312. this.blurKernelY = value;
  52313. },
  52314. enumerable: true,
  52315. configurable: true
  52316. });
  52317. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52318. get: function () {
  52319. return this._blurKernelX;
  52320. },
  52321. set: function (value) {
  52322. if (this._blurKernelX === value) {
  52323. return;
  52324. }
  52325. this._blurKernelX = value;
  52326. this._preparePostProcesses();
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52332. get: function () {
  52333. return this._blurKernelY;
  52334. },
  52335. set: function (value) {
  52336. if (this._blurKernelY === value) {
  52337. return;
  52338. }
  52339. this._blurKernelY = value;
  52340. this._preparePostProcesses();
  52341. },
  52342. enumerable: true,
  52343. configurable: true
  52344. });
  52345. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52346. var engine = this.getScene().getEngine();
  52347. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52348. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52349. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52350. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52351. };
  52352. MirrorTexture.prototype._onRatioRescale = function () {
  52353. if (this._sizeRatio) {
  52354. this.resize(this._initialSizeParameter);
  52355. if (!this._adaptiveBlurKernel) {
  52356. this._preparePostProcesses();
  52357. }
  52358. }
  52359. if (this._adaptiveBlurKernel) {
  52360. this._autoComputeBlurKernel();
  52361. }
  52362. };
  52363. MirrorTexture.prototype._preparePostProcesses = function () {
  52364. this.clearPostProcesses(true);
  52365. if (this._blurKernelX && this._blurKernelY) {
  52366. var engine = this.getScene().getEngine();
  52367. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52368. 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);
  52369. this._blurX.autoClear = false;
  52370. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52371. this._blurX.outputTexture = this._texture;
  52372. }
  52373. else {
  52374. this._blurX.alwaysForcePOT = true;
  52375. }
  52376. 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);
  52377. this._blurY.autoClear = false;
  52378. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52379. this.addPostProcess(this._blurX);
  52380. this.addPostProcess(this._blurY);
  52381. }
  52382. else {
  52383. if (this._blurY) {
  52384. this.removePostProcess(this._blurY);
  52385. this._blurY.dispose();
  52386. this._blurY = null;
  52387. }
  52388. if (this._blurX) {
  52389. this.removePostProcess(this._blurX);
  52390. this._blurX.dispose();
  52391. this._blurX = null;
  52392. }
  52393. }
  52394. };
  52395. MirrorTexture.prototype.clone = function () {
  52396. var scene = this.getScene();
  52397. if (!scene) {
  52398. return this;
  52399. }
  52400. var textureSize = this.getSize();
  52401. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52402. // Base texture
  52403. newTexture.hasAlpha = this.hasAlpha;
  52404. newTexture.level = this.level;
  52405. // Mirror Texture
  52406. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52407. if (this.renderList) {
  52408. newTexture.renderList = this.renderList.slice(0);
  52409. }
  52410. return newTexture;
  52411. };
  52412. MirrorTexture.prototype.serialize = function () {
  52413. if (!this.name) {
  52414. return null;
  52415. }
  52416. var serializationObject = _super.prototype.serialize.call(this);
  52417. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52418. return serializationObject;
  52419. };
  52420. return MirrorTexture;
  52421. }(BABYLON.RenderTargetTexture));
  52422. BABYLON.MirrorTexture = MirrorTexture;
  52423. })(BABYLON || (BABYLON = {}));
  52424. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52425. var BABYLON;
  52426. (function (BABYLON) {
  52427. /**
  52428. * Creates a refraction texture used by refraction channel of the standard material.
  52429. * @param name the texture name
  52430. * @param size size of the underlying texture
  52431. * @param scene root scene
  52432. */
  52433. var RefractionTexture = /** @class */ (function (_super) {
  52434. __extends(RefractionTexture, _super);
  52435. function RefractionTexture(name, size, scene, generateMipMaps) {
  52436. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52437. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52438. _this.depth = 2.0;
  52439. _this.onBeforeRenderObservable.add(function () {
  52440. scene.clipPlane = _this.refractionPlane;
  52441. });
  52442. _this.onAfterRenderObservable.add(function () {
  52443. delete scene.clipPlane;
  52444. });
  52445. return _this;
  52446. }
  52447. RefractionTexture.prototype.clone = function () {
  52448. var scene = this.getScene();
  52449. if (!scene) {
  52450. return this;
  52451. }
  52452. var textureSize = this.getSize();
  52453. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52454. // Base texture
  52455. newTexture.hasAlpha = this.hasAlpha;
  52456. newTexture.level = this.level;
  52457. // Refraction Texture
  52458. newTexture.refractionPlane = this.refractionPlane.clone();
  52459. if (this.renderList) {
  52460. newTexture.renderList = this.renderList.slice(0);
  52461. }
  52462. newTexture.depth = this.depth;
  52463. return newTexture;
  52464. };
  52465. RefractionTexture.prototype.serialize = function () {
  52466. if (!this.name) {
  52467. return null;
  52468. }
  52469. var serializationObject = _super.prototype.serialize.call(this);
  52470. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52471. serializationObject.depth = this.depth;
  52472. return serializationObject;
  52473. };
  52474. return RefractionTexture;
  52475. }(BABYLON.RenderTargetTexture));
  52476. BABYLON.RefractionTexture = RefractionTexture;
  52477. })(BABYLON || (BABYLON = {}));
  52478. //# sourceMappingURL=babylon.refractionTexture.js.map
  52479. var BABYLON;
  52480. (function (BABYLON) {
  52481. var DynamicTexture = /** @class */ (function (_super) {
  52482. __extends(DynamicTexture, _super);
  52483. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52484. if (scene === void 0) { scene = null; }
  52485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52486. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52487. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52488. _this.name = name;
  52489. _this._engine = _this.getScene().getEngine();
  52490. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52491. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52492. _this._generateMipMaps = generateMipMaps;
  52493. if (options.getContext) {
  52494. _this._canvas = options;
  52495. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52496. }
  52497. else {
  52498. _this._canvas = document.createElement("canvas");
  52499. if (options.width) {
  52500. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52501. }
  52502. else {
  52503. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52504. }
  52505. }
  52506. var textureSize = _this.getSize();
  52507. _this._canvas.width = textureSize.width;
  52508. _this._canvas.height = textureSize.height;
  52509. _this._context = _this._canvas.getContext("2d");
  52510. return _this;
  52511. }
  52512. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52513. get: function () {
  52514. return true;
  52515. },
  52516. enumerable: true,
  52517. configurable: true
  52518. });
  52519. DynamicTexture.prototype._recreate = function (textureSize) {
  52520. this._canvas.width = textureSize.width;
  52521. this._canvas.height = textureSize.height;
  52522. this.releaseInternalTexture();
  52523. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52524. };
  52525. DynamicTexture.prototype.scale = function (ratio) {
  52526. var textureSize = this.getSize();
  52527. textureSize.width *= ratio;
  52528. textureSize.height *= ratio;
  52529. this._recreate(textureSize);
  52530. };
  52531. DynamicTexture.prototype.scaleTo = function (width, height) {
  52532. var textureSize = this.getSize();
  52533. textureSize.width = width;
  52534. textureSize.height = height;
  52535. this._recreate(textureSize);
  52536. };
  52537. DynamicTexture.prototype.getContext = function () {
  52538. return this._context;
  52539. };
  52540. DynamicTexture.prototype.clear = function () {
  52541. var size = this.getSize();
  52542. this._context.fillRect(0, 0, size.width, size.height);
  52543. };
  52544. DynamicTexture.prototype.update = function (invertY) {
  52545. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52546. };
  52547. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52548. if (update === void 0) { update = true; }
  52549. var size = this.getSize();
  52550. if (clearColor) {
  52551. this._context.fillStyle = clearColor;
  52552. this._context.fillRect(0, 0, size.width, size.height);
  52553. }
  52554. this._context.font = font;
  52555. if (x === null || x === undefined) {
  52556. var textSize = this._context.measureText(text);
  52557. x = (size.width - textSize.width) / 2;
  52558. }
  52559. if (y === null || y === undefined) {
  52560. var fontSize = parseInt((font.replace(/\D/g, '')));
  52561. ;
  52562. y = (size.height / 2) + (fontSize / 3.65);
  52563. }
  52564. this._context.fillStyle = color;
  52565. this._context.fillText(text, x, y);
  52566. if (update) {
  52567. this.update(invertY);
  52568. }
  52569. };
  52570. DynamicTexture.prototype.clone = function () {
  52571. var scene = this.getScene();
  52572. if (!scene) {
  52573. return this;
  52574. }
  52575. var textureSize = this.getSize();
  52576. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52577. // Base texture
  52578. newTexture.hasAlpha = this.hasAlpha;
  52579. newTexture.level = this.level;
  52580. // Dynamic Texture
  52581. newTexture.wrapU = this.wrapU;
  52582. newTexture.wrapV = this.wrapV;
  52583. return newTexture;
  52584. };
  52585. DynamicTexture.prototype._rebuild = function () {
  52586. this.update();
  52587. };
  52588. return DynamicTexture;
  52589. }(BABYLON.Texture));
  52590. BABYLON.DynamicTexture = DynamicTexture;
  52591. })(BABYLON || (BABYLON = {}));
  52592. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52593. var BABYLON;
  52594. (function (BABYLON) {
  52595. var VideoTexture = /** @class */ (function (_super) {
  52596. __extends(VideoTexture, _super);
  52597. /**
  52598. * Creates a video texture.
  52599. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52600. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52601. * @param {BABYLON.Scene} scene is obviously the current scene.
  52602. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52603. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52604. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52605. */
  52606. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52607. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52608. if (invertY === void 0) { invertY = false; }
  52609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52610. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52611. _this._autoLaunch = true;
  52612. var urls = null;
  52613. _this.name = name;
  52614. if (urlsOrVideo instanceof HTMLVideoElement) {
  52615. _this.video = urlsOrVideo;
  52616. }
  52617. else {
  52618. urls = urlsOrVideo;
  52619. _this.video = document.createElement("video");
  52620. _this.video.autoplay = false;
  52621. _this.video.loop = true;
  52622. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52623. }
  52624. _this._engine = _this.getScene().getEngine();
  52625. _this._generateMipMaps = generateMipMaps;
  52626. _this._samplingMode = samplingMode;
  52627. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52628. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52629. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52630. }
  52631. else {
  52632. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52633. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52634. _this._generateMipMaps = false;
  52635. }
  52636. if (urls) {
  52637. _this.video.addEventListener("canplay", function () {
  52638. if (_this._texture === undefined) {
  52639. _this._createTexture();
  52640. }
  52641. });
  52642. urls.forEach(function (url) {
  52643. var source = document.createElement("source");
  52644. source.src = url;
  52645. _this.video.appendChild(source);
  52646. });
  52647. }
  52648. else {
  52649. _this._createTexture();
  52650. }
  52651. _this._lastUpdate = BABYLON.Tools.Now;
  52652. return _this;
  52653. }
  52654. VideoTexture.prototype.__setTextureReady = function () {
  52655. if (this._texture) {
  52656. this._texture.isReady = true;
  52657. }
  52658. };
  52659. VideoTexture.prototype._createTexture = function () {
  52660. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52661. if (this._autoLaunch) {
  52662. this._autoLaunch = false;
  52663. this.video.play();
  52664. }
  52665. this._setTextureReady = this.__setTextureReady.bind(this);
  52666. this.video.addEventListener("playing", this._setTextureReady);
  52667. };
  52668. VideoTexture.prototype._rebuild = function () {
  52669. this.update();
  52670. };
  52671. VideoTexture.prototype.update = function () {
  52672. var now = BABYLON.Tools.Now;
  52673. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52674. return false;
  52675. }
  52676. this._lastUpdate = now;
  52677. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52678. return true;
  52679. };
  52680. VideoTexture.prototype.dispose = function () {
  52681. _super.prototype.dispose.call(this);
  52682. this.video.removeEventListener("playing", this._setTextureReady);
  52683. };
  52684. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52685. var video = document.createElement("video");
  52686. var constraintsDeviceId;
  52687. if (constraints && constraints.deviceId) {
  52688. constraintsDeviceId = {
  52689. exact: constraints.deviceId
  52690. };
  52691. }
  52692. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52693. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52694. if (navigator.getUserMedia) {
  52695. navigator.getUserMedia({
  52696. video: {
  52697. deviceId: constraintsDeviceId,
  52698. width: {
  52699. min: (constraints && constraints.minWidth) || 256,
  52700. max: (constraints && constraints.maxWidth) || 640
  52701. },
  52702. height: {
  52703. min: (constraints && constraints.minHeight) || 256,
  52704. max: (constraints && constraints.maxHeight) || 480
  52705. }
  52706. }
  52707. }, function (stream) {
  52708. if (video.mozSrcObject !== undefined) {
  52709. video.mozSrcObject = stream;
  52710. }
  52711. else {
  52712. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52713. }
  52714. video.play();
  52715. if (onReady) {
  52716. onReady(new VideoTexture("video", video, scene, true, true));
  52717. }
  52718. }, function (e) {
  52719. BABYLON.Tools.Error(e.name);
  52720. });
  52721. }
  52722. };
  52723. return VideoTexture;
  52724. }(BABYLON.Texture));
  52725. BABYLON.VideoTexture = VideoTexture;
  52726. })(BABYLON || (BABYLON = {}));
  52727. //# sourceMappingURL=babylon.videoTexture.js.map
  52728. var BABYLON;
  52729. (function (BABYLON) {
  52730. var RawTexture = /** @class */ (function (_super) {
  52731. __extends(RawTexture, _super);
  52732. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52733. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52734. if (invertY === void 0) { invertY = false; }
  52735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52736. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52737. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52738. _this.format = format;
  52739. _this._engine = scene.getEngine();
  52740. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52741. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52742. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52743. return _this;
  52744. }
  52745. RawTexture.prototype.update = function (data) {
  52746. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52747. };
  52748. // Statics
  52749. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52750. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52751. if (invertY === void 0) { invertY = false; }
  52752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52753. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52754. };
  52755. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52757. if (invertY === void 0) { invertY = false; }
  52758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52759. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52760. };
  52761. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52763. if (invertY === void 0) { invertY = false; }
  52764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52765. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52766. };
  52767. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52769. if (invertY === void 0) { invertY = false; }
  52770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52771. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52772. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52773. };
  52774. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52775. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52776. if (invertY === void 0) { invertY = false; }
  52777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52778. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52779. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52780. };
  52781. return RawTexture;
  52782. }(BABYLON.Texture));
  52783. BABYLON.RawTexture = RawTexture;
  52784. })(BABYLON || (BABYLON = {}));
  52785. //# sourceMappingURL=babylon.rawTexture.js.map
  52786. var BABYLON;
  52787. (function (BABYLON) {
  52788. var PostProcess = /** @class */ (function () {
  52789. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52790. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52791. if (defines === void 0) { defines = null; }
  52792. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52793. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52794. if (blockCompilation === void 0) { blockCompilation = false; }
  52795. this.name = name;
  52796. this.width = -1;
  52797. this.height = -1;
  52798. this.autoClear = true;
  52799. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52800. this.animations = new Array();
  52801. /*
  52802. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52803. Can only be used on a single postprocess or on the last one of a chain.
  52804. */
  52805. this.enablePixelPerfectMode = false;
  52806. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52807. this.alwaysForcePOT = false;
  52808. this.samples = 1;
  52809. this.adaptScaleToCurrentViewport = false;
  52810. this._reusable = false;
  52811. this._textures = new BABYLON.SmartArray(2);
  52812. this._currentRenderTextureInd = 0;
  52813. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52814. this._texelSize = BABYLON.Vector2.Zero();
  52815. // Events
  52816. /**
  52817. * An event triggered when the postprocess is activated.
  52818. * @type {BABYLON.Observable}
  52819. */
  52820. this.onActivateObservable = new BABYLON.Observable();
  52821. /**
  52822. * An event triggered when the postprocess changes its size.
  52823. * @type {BABYLON.Observable}
  52824. */
  52825. this.onSizeChangedObservable = new BABYLON.Observable();
  52826. /**
  52827. * An event triggered when the postprocess applies its effect.
  52828. * @type {BABYLON.Observable}
  52829. */
  52830. this.onApplyObservable = new BABYLON.Observable();
  52831. /**
  52832. * An event triggered before rendering the postprocess
  52833. * @type {BABYLON.Observable}
  52834. */
  52835. this.onBeforeRenderObservable = new BABYLON.Observable();
  52836. /**
  52837. * An event triggered after rendering the postprocess
  52838. * @type {BABYLON.Observable}
  52839. */
  52840. this.onAfterRenderObservable = new BABYLON.Observable();
  52841. if (camera != null) {
  52842. this._camera = camera;
  52843. this._scene = camera.getScene();
  52844. camera.attachPostProcess(this);
  52845. this._engine = this._scene.getEngine();
  52846. this._scene.postProcesses.push(this);
  52847. }
  52848. else if (engine) {
  52849. this._engine = engine;
  52850. this._engine.postProcesses.push(this);
  52851. }
  52852. this._options = options;
  52853. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52854. this._reusable = reusable || false;
  52855. this._textureType = textureType;
  52856. this._samplers = samplers || [];
  52857. this._samplers.push("textureSampler");
  52858. this._fragmentUrl = fragmentUrl;
  52859. this._vertexUrl = vertexUrl;
  52860. this._parameters = parameters || [];
  52861. this._parameters.push("scale");
  52862. this._indexParameters = indexParameters;
  52863. if (!blockCompilation) {
  52864. this.updateEffect(defines);
  52865. }
  52866. }
  52867. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52868. set: function (callback) {
  52869. if (this._onActivateObserver) {
  52870. this.onActivateObservable.remove(this._onActivateObserver);
  52871. }
  52872. if (callback) {
  52873. this._onActivateObserver = this.onActivateObservable.add(callback);
  52874. }
  52875. },
  52876. enumerable: true,
  52877. configurable: true
  52878. });
  52879. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  52880. set: function (callback) {
  52881. if (this._onSizeChangedObserver) {
  52882. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  52883. }
  52884. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  52885. },
  52886. enumerable: true,
  52887. configurable: true
  52888. });
  52889. Object.defineProperty(PostProcess.prototype, "onApply", {
  52890. set: function (callback) {
  52891. if (this._onApplyObserver) {
  52892. this.onApplyObservable.remove(this._onApplyObserver);
  52893. }
  52894. this._onApplyObserver = this.onApplyObservable.add(callback);
  52895. },
  52896. enumerable: true,
  52897. configurable: true
  52898. });
  52899. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  52900. set: function (callback) {
  52901. if (this._onBeforeRenderObserver) {
  52902. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  52903. }
  52904. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  52905. },
  52906. enumerable: true,
  52907. configurable: true
  52908. });
  52909. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  52910. set: function (callback) {
  52911. if (this._onAfterRenderObserver) {
  52912. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  52913. }
  52914. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  52915. },
  52916. enumerable: true,
  52917. configurable: true
  52918. });
  52919. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  52920. get: function () {
  52921. return this._textures.data[this._currentRenderTextureInd];
  52922. },
  52923. set: function (value) {
  52924. this._forcedOutputTexture = value;
  52925. },
  52926. enumerable: true,
  52927. configurable: true
  52928. });
  52929. PostProcess.prototype.getCamera = function () {
  52930. return this._camera;
  52931. };
  52932. Object.defineProperty(PostProcess.prototype, "texelSize", {
  52933. get: function () {
  52934. if (this._shareOutputWithPostProcess) {
  52935. return this._shareOutputWithPostProcess.texelSize;
  52936. }
  52937. if (this._forcedOutputTexture) {
  52938. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  52939. }
  52940. return this._texelSize;
  52941. },
  52942. enumerable: true,
  52943. configurable: true
  52944. });
  52945. PostProcess.prototype.getEngine = function () {
  52946. return this._engine;
  52947. };
  52948. PostProcess.prototype.getEffect = function () {
  52949. return this._effect;
  52950. };
  52951. PostProcess.prototype.shareOutputWith = function (postProcess) {
  52952. this._disposeTextures();
  52953. this._shareOutputWithPostProcess = postProcess;
  52954. return this;
  52955. };
  52956. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  52957. if (defines === void 0) { defines = null; }
  52958. if (uniforms === void 0) { uniforms = null; }
  52959. if (samplers === void 0) { samplers = null; }
  52960. 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);
  52961. };
  52962. PostProcess.prototype.isReusable = function () {
  52963. return this._reusable;
  52964. };
  52965. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  52966. PostProcess.prototype.markTextureDirty = function () {
  52967. this.width = -1;
  52968. };
  52969. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  52970. var _this = this;
  52971. if (sourceTexture === void 0) { sourceTexture = null; }
  52972. camera = camera || this._camera;
  52973. var scene = camera.getScene();
  52974. var engine = scene.getEngine();
  52975. var maxSize = engine.getCaps().maxTextureSize;
  52976. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  52977. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  52978. var desiredWidth = (this._options.width || requiredWidth);
  52979. var desiredHeight = this._options.height || requiredHeight;
  52980. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  52981. if (this.adaptScaleToCurrentViewport) {
  52982. var currentViewport = engine.currentViewport;
  52983. if (currentViewport) {
  52984. desiredWidth *= currentViewport.width;
  52985. desiredHeight *= currentViewport.height;
  52986. }
  52987. }
  52988. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  52989. if (!this._options.width) {
  52990. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  52991. }
  52992. if (!this._options.height) {
  52993. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  52994. }
  52995. }
  52996. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  52997. if (this._textures.length > 0) {
  52998. for (var i = 0; i < this._textures.length; i++) {
  52999. this._engine._releaseTexture(this._textures.data[i]);
  53000. }
  53001. this._textures.reset();
  53002. }
  53003. this.width = desiredWidth;
  53004. this.height = desiredHeight;
  53005. var textureSize = { width: this.width, height: this.height };
  53006. var textureOptions = {
  53007. generateMipMaps: false,
  53008. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53009. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53010. samplingMode: this.renderTargetSamplingMode,
  53011. type: this._textureType
  53012. };
  53013. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53014. if (this._reusable) {
  53015. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53016. }
  53017. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53018. this.onSizeChangedObservable.notifyObservers(this);
  53019. }
  53020. this._textures.forEach(function (texture) {
  53021. if (texture.samples !== _this.samples) {
  53022. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53023. }
  53024. });
  53025. }
  53026. var target;
  53027. if (this._shareOutputWithPostProcess) {
  53028. target = this._shareOutputWithPostProcess.outputTexture;
  53029. }
  53030. else if (this._forcedOutputTexture) {
  53031. target = this._forcedOutputTexture;
  53032. this.width = this._forcedOutputTexture.width;
  53033. this.height = this._forcedOutputTexture.height;
  53034. }
  53035. else {
  53036. target = this.outputTexture;
  53037. }
  53038. if (this.enablePixelPerfectMode) {
  53039. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53040. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53041. }
  53042. else {
  53043. this._scaleRatio.copyFromFloats(1, 1);
  53044. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53045. }
  53046. this.onActivateObservable.notifyObservers(camera);
  53047. // Clear
  53048. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53049. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53050. }
  53051. if (this._reusable) {
  53052. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53053. }
  53054. };
  53055. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53056. get: function () {
  53057. return this._effect.isSupported;
  53058. },
  53059. enumerable: true,
  53060. configurable: true
  53061. });
  53062. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53063. get: function () {
  53064. if (this._shareOutputWithPostProcess) {
  53065. return this._shareOutputWithPostProcess.aspectRatio;
  53066. }
  53067. if (this._forcedOutputTexture) {
  53068. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53069. }
  53070. return this.width / this.height;
  53071. },
  53072. enumerable: true,
  53073. configurable: true
  53074. });
  53075. PostProcess.prototype.apply = function () {
  53076. // Check
  53077. if (!this._effect || !this._effect.isReady())
  53078. return null;
  53079. // States
  53080. this._engine.enableEffect(this._effect);
  53081. this._engine.setState(false);
  53082. this._engine.setDepthBuffer(false);
  53083. this._engine.setDepthWrite(false);
  53084. // Alpha
  53085. this._engine.setAlphaMode(this.alphaMode);
  53086. if (this.alphaConstants) {
  53087. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53088. }
  53089. // Texture
  53090. var source;
  53091. if (this._shareOutputWithPostProcess) {
  53092. source = this._shareOutputWithPostProcess.outputTexture;
  53093. }
  53094. else if (this._forcedOutputTexture) {
  53095. source = this._forcedOutputTexture;
  53096. }
  53097. else {
  53098. source = this.outputTexture;
  53099. }
  53100. this._effect._bindTexture("textureSampler", source);
  53101. // Parameters
  53102. this._effect.setVector2("scale", this._scaleRatio);
  53103. this.onApplyObservable.notifyObservers(this._effect);
  53104. return this._effect;
  53105. };
  53106. PostProcess.prototype._disposeTextures = function () {
  53107. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53108. return;
  53109. }
  53110. if (this._textures.length > 0) {
  53111. for (var i = 0; i < this._textures.length; i++) {
  53112. this._engine._releaseTexture(this._textures.data[i]);
  53113. }
  53114. }
  53115. this._textures.dispose();
  53116. };
  53117. PostProcess.prototype.dispose = function (camera) {
  53118. camera = camera || this._camera;
  53119. this._disposeTextures();
  53120. if (this._scene) {
  53121. var index_1 = this._scene.postProcesses.indexOf(this);
  53122. if (index_1 !== -1) {
  53123. this._scene.postProcesses.splice(index_1, 1);
  53124. }
  53125. }
  53126. else {
  53127. var index_2 = this._engine.postProcesses.indexOf(this);
  53128. if (index_2 !== -1) {
  53129. this._engine.postProcesses.splice(index_2, 1);
  53130. }
  53131. }
  53132. if (!camera) {
  53133. return;
  53134. }
  53135. camera.detachPostProcess(this);
  53136. var index = camera._postProcesses.indexOf(this);
  53137. if (index === 0 && camera._postProcesses.length > 0) {
  53138. this._camera._postProcesses[0].markTextureDirty();
  53139. }
  53140. this.onActivateObservable.clear();
  53141. this.onAfterRenderObservable.clear();
  53142. this.onApplyObservable.clear();
  53143. this.onBeforeRenderObservable.clear();
  53144. this.onSizeChangedObservable.clear();
  53145. };
  53146. return PostProcess;
  53147. }());
  53148. BABYLON.PostProcess = PostProcess;
  53149. })(BABYLON || (BABYLON = {}));
  53150. //# sourceMappingURL=babylon.postProcess.js.map
  53151. var BABYLON;
  53152. (function (BABYLON) {
  53153. var PassPostProcess = /** @class */ (function (_super) {
  53154. __extends(PassPostProcess, _super);
  53155. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53156. if (camera === void 0) { camera = null; }
  53157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53158. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53159. }
  53160. return PassPostProcess;
  53161. }(BABYLON.PostProcess));
  53162. BABYLON.PassPostProcess = PassPostProcess;
  53163. })(BABYLON || (BABYLON = {}));
  53164. //# sourceMappingURL=babylon.passPostProcess.js.map
  53165. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53166. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53167. s = arguments[i];
  53168. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53169. t[p] = s[p];
  53170. }
  53171. return t;
  53172. };
  53173. var BABYLON;
  53174. (function (BABYLON) {
  53175. var ShadowGenerator = /** @class */ (function () {
  53176. /**
  53177. * Creates a ShadowGenerator object.
  53178. * A ShadowGenerator is the required tool to use the shadows.
  53179. * Each light casting shadows needs to use its own ShadowGenerator.
  53180. * Required parameters :
  53181. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53182. * - `light`: the light object generating the shadows.
  53183. * - `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.
  53184. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53185. */
  53186. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53187. // Members
  53188. this._bias = 0.00005;
  53189. this._blurBoxOffset = 1;
  53190. this._blurScale = 2;
  53191. this._blurKernel = 1;
  53192. this._useKernelBlur = false;
  53193. this._filter = ShadowGenerator.FILTER_NONE;
  53194. this._darkness = 0;
  53195. this._transparencyShadow = false;
  53196. /**
  53197. * Controls the extent to which the shadows fade out at the edge of the frustum
  53198. * Used only by directionals and spots
  53199. */
  53200. this.frustumEdgeFalloff = 0;
  53201. this.forceBackFacesOnly = false;
  53202. this._lightDirection = BABYLON.Vector3.Zero();
  53203. this._viewMatrix = BABYLON.Matrix.Zero();
  53204. this._projectionMatrix = BABYLON.Matrix.Zero();
  53205. this._transformMatrix = BABYLON.Matrix.Zero();
  53206. this._currentFaceIndex = 0;
  53207. this._currentFaceIndexCache = 0;
  53208. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53209. this._mapSize = mapSize;
  53210. this._light = light;
  53211. this._scene = light.getScene();
  53212. light._shadowGenerator = this;
  53213. // Texture type fallback from float to int if not supported.
  53214. var caps = this._scene.getEngine().getCaps();
  53215. if (!useFullFloatFirst) {
  53216. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53217. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53218. }
  53219. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53220. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53221. }
  53222. else {
  53223. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53224. }
  53225. }
  53226. else {
  53227. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53228. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53229. }
  53230. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53231. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53232. }
  53233. else {
  53234. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53235. }
  53236. }
  53237. this._initializeGenerator();
  53238. }
  53239. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53240. // Static
  53241. get: function () {
  53242. return ShadowGenerator._FILTER_NONE;
  53243. },
  53244. enumerable: true,
  53245. configurable: true
  53246. });
  53247. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53248. get: function () {
  53249. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53250. },
  53251. enumerable: true,
  53252. configurable: true
  53253. });
  53254. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53255. get: function () {
  53256. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53257. },
  53258. enumerable: true,
  53259. configurable: true
  53260. });
  53261. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53262. get: function () {
  53263. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53264. },
  53265. enumerable: true,
  53266. configurable: true
  53267. });
  53268. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53269. get: function () {
  53270. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53276. get: function () {
  53277. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53278. },
  53279. enumerable: true,
  53280. configurable: true
  53281. });
  53282. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53283. get: function () {
  53284. return this._bias;
  53285. },
  53286. set: function (bias) {
  53287. this._bias = bias;
  53288. },
  53289. enumerable: true,
  53290. configurable: true
  53291. });
  53292. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53293. get: function () {
  53294. return this._blurBoxOffset;
  53295. },
  53296. set: function (value) {
  53297. if (this._blurBoxOffset === value) {
  53298. return;
  53299. }
  53300. this._blurBoxOffset = value;
  53301. this._disposeBlurPostProcesses();
  53302. },
  53303. enumerable: true,
  53304. configurable: true
  53305. });
  53306. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53307. get: function () {
  53308. return this._blurScale;
  53309. },
  53310. set: function (value) {
  53311. if (this._blurScale === value) {
  53312. return;
  53313. }
  53314. this._blurScale = value;
  53315. this._disposeBlurPostProcesses();
  53316. },
  53317. enumerable: true,
  53318. configurable: true
  53319. });
  53320. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53321. get: function () {
  53322. return this._blurKernel;
  53323. },
  53324. set: function (value) {
  53325. if (this._blurKernel === value) {
  53326. return;
  53327. }
  53328. this._blurKernel = value;
  53329. this._disposeBlurPostProcesses();
  53330. },
  53331. enumerable: true,
  53332. configurable: true
  53333. });
  53334. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53335. get: function () {
  53336. return this._useKernelBlur;
  53337. },
  53338. set: function (value) {
  53339. if (this._useKernelBlur === value) {
  53340. return;
  53341. }
  53342. this._useKernelBlur = value;
  53343. this._disposeBlurPostProcesses();
  53344. },
  53345. enumerable: true,
  53346. configurable: true
  53347. });
  53348. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53349. get: function () {
  53350. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53351. },
  53352. set: function (value) {
  53353. this._depthScale = value;
  53354. },
  53355. enumerable: true,
  53356. configurable: true
  53357. });
  53358. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53359. get: function () {
  53360. return this._filter;
  53361. },
  53362. set: function (value) {
  53363. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53364. if (this._light.needCube()) {
  53365. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53366. this.useExponentialShadowMap = true;
  53367. return;
  53368. }
  53369. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53370. this.useCloseExponentialShadowMap = true;
  53371. return;
  53372. }
  53373. }
  53374. if (this._filter === value) {
  53375. return;
  53376. }
  53377. this._filter = value;
  53378. this._disposeBlurPostProcesses();
  53379. this._applyFilterValues();
  53380. this._light._markMeshesAsLightDirty();
  53381. },
  53382. enumerable: true,
  53383. configurable: true
  53384. });
  53385. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53386. get: function () {
  53387. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53388. },
  53389. set: function (value) {
  53390. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53391. return;
  53392. }
  53393. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53394. },
  53395. enumerable: true,
  53396. configurable: true
  53397. });
  53398. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53399. get: function () {
  53400. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53401. return this.useExponentialShadowMap;
  53402. },
  53403. set: function (value) {
  53404. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53405. this.useExponentialShadowMap = value;
  53406. },
  53407. enumerable: true,
  53408. configurable: true
  53409. });
  53410. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53411. get: function () {
  53412. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53413. return this.useBlurExponentialShadowMap;
  53414. },
  53415. set: function (value) {
  53416. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53417. this.useBlurExponentialShadowMap = value;
  53418. },
  53419. enumerable: true,
  53420. configurable: true
  53421. });
  53422. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53423. get: function () {
  53424. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53425. },
  53426. set: function (value) {
  53427. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53428. return;
  53429. }
  53430. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53431. },
  53432. enumerable: true,
  53433. configurable: true
  53434. });
  53435. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53436. get: function () {
  53437. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53438. },
  53439. set: function (value) {
  53440. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53441. return;
  53442. }
  53443. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53444. },
  53445. enumerable: true,
  53446. configurable: true
  53447. });
  53448. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53449. get: function () {
  53450. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53451. },
  53452. set: function (value) {
  53453. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53454. return;
  53455. }
  53456. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53457. },
  53458. enumerable: true,
  53459. configurable: true
  53460. });
  53461. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53462. get: function () {
  53463. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53464. },
  53465. set: function (value) {
  53466. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53467. return;
  53468. }
  53469. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53470. },
  53471. enumerable: true,
  53472. configurable: true
  53473. });
  53474. /**
  53475. * Returns the darkness value (float).
  53476. */
  53477. ShadowGenerator.prototype.getDarkness = function () {
  53478. return this._darkness;
  53479. };
  53480. /**
  53481. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53482. * Returns the ShadowGenerator.
  53483. */
  53484. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53485. if (darkness >= 1.0)
  53486. this._darkness = 1.0;
  53487. else if (darkness <= 0.0)
  53488. this._darkness = 0.0;
  53489. else
  53490. this._darkness = darkness;
  53491. return this;
  53492. };
  53493. /**
  53494. * Sets the ability to have transparent shadow (boolean).
  53495. * Returns the ShadowGenerator.
  53496. */
  53497. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53498. this._transparencyShadow = hasShadow;
  53499. return this;
  53500. };
  53501. /**
  53502. * Returns a RenderTargetTexture object : the shadow map texture.
  53503. */
  53504. ShadowGenerator.prototype.getShadowMap = function () {
  53505. return this._shadowMap;
  53506. };
  53507. /**
  53508. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53509. */
  53510. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53511. if (this._shadowMap2) {
  53512. return this._shadowMap2;
  53513. }
  53514. return this._shadowMap;
  53515. };
  53516. /**
  53517. * Helper function to add a mesh and its descendants to the list of shadow casters
  53518. * @param mesh Mesh to add
  53519. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53520. */
  53521. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53522. if (includeDescendants === void 0) { includeDescendants = true; }
  53523. if (!this._shadowMap) {
  53524. return this;
  53525. }
  53526. if (!this._shadowMap.renderList) {
  53527. this._shadowMap.renderList = [];
  53528. }
  53529. this._shadowMap.renderList.push(mesh);
  53530. if (includeDescendants) {
  53531. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53532. }
  53533. return this;
  53534. var _a;
  53535. };
  53536. /**
  53537. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53538. * @param mesh Mesh to remove
  53539. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53540. */
  53541. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53542. if (includeDescendants === void 0) { includeDescendants = true; }
  53543. if (!this._shadowMap || !this._shadowMap.renderList) {
  53544. return this;
  53545. }
  53546. var index = this._shadowMap.renderList.indexOf(mesh);
  53547. if (index !== -1) {
  53548. this._shadowMap.renderList.splice(index, 1);
  53549. }
  53550. if (includeDescendants) {
  53551. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53552. var child = _a[_i];
  53553. this.removeShadowCaster(child);
  53554. }
  53555. }
  53556. return this;
  53557. };
  53558. /**
  53559. * Returns the associated light object.
  53560. */
  53561. ShadowGenerator.prototype.getLight = function () {
  53562. return this._light;
  53563. };
  53564. ShadowGenerator.prototype._initializeGenerator = function () {
  53565. this._light._markMeshesAsLightDirty();
  53566. this._initializeShadowMap();
  53567. };
  53568. ShadowGenerator.prototype._initializeShadowMap = function () {
  53569. var _this = this;
  53570. // Render target
  53571. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53572. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53573. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53574. this._shadowMap.anisotropicFilteringLevel = 1;
  53575. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53576. this._shadowMap.renderParticles = false;
  53577. this._shadowMap.ignoreCameraViewport = true;
  53578. // Record Face Index before render.
  53579. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53580. _this._currentFaceIndex = faceIndex;
  53581. });
  53582. // Custom render function.
  53583. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53584. // Blur if required afer render.
  53585. this._shadowMap.onAfterUnbindObservable.add(function () {
  53586. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53587. return;
  53588. }
  53589. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  53590. _this._initializeBlurRTTAndPostProcesses();
  53591. }
  53592. var shadowMap = _this.getShadowMapForRendering();
  53593. if (shadowMap) {
  53594. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53595. }
  53596. });
  53597. // Clear according to the chosen filter.
  53598. this._shadowMap.onClearObservable.add(function (engine) {
  53599. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53600. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53601. }
  53602. else {
  53603. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53604. }
  53605. });
  53606. };
  53607. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53608. var _this = this;
  53609. var engine = this._scene.getEngine();
  53610. var targetSize = this._mapSize / this.blurScale;
  53611. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53612. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53613. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53614. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53615. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53616. }
  53617. if (this.useKernelBlur) {
  53618. 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);
  53619. this._kernelBlurXPostprocess.width = targetSize;
  53620. this._kernelBlurXPostprocess.height = targetSize;
  53621. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53622. effect.setTexture("textureSampler", _this._shadowMap);
  53623. });
  53624. 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);
  53625. this._kernelBlurXPostprocess.autoClear = false;
  53626. this._kernelBlurYPostprocess.autoClear = false;
  53627. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53628. this._kernelBlurXPostprocess.packedFloat = true;
  53629. this._kernelBlurYPostprocess.packedFloat = true;
  53630. }
  53631. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53632. }
  53633. else {
  53634. 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);
  53635. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53636. effect.setFloat2("screenSize", targetSize, targetSize);
  53637. effect.setTexture("textureSampler", _this._shadowMap);
  53638. });
  53639. this._boxBlurPostprocess.autoClear = false;
  53640. this._blurPostProcesses = [this._boxBlurPostprocess];
  53641. }
  53642. };
  53643. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53644. var index;
  53645. var engine = this._scene.getEngine();
  53646. if (depthOnlySubMeshes.length) {
  53647. engine.setColorWrite(false);
  53648. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53649. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53650. }
  53651. engine.setColorWrite(true);
  53652. }
  53653. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53654. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53655. }
  53656. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53657. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53658. }
  53659. if (this._transparencyShadow) {
  53660. for (index = 0; index < transparentSubMeshes.length; index++) {
  53661. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53662. }
  53663. }
  53664. };
  53665. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53666. var _this = this;
  53667. var mesh = subMesh.getRenderingMesh();
  53668. var scene = this._scene;
  53669. var engine = scene.getEngine();
  53670. var material = subMesh.getMaterial();
  53671. if (!material) {
  53672. return;
  53673. }
  53674. // Culling
  53675. engine.setState(material.backFaceCulling);
  53676. // Managing instances
  53677. var batch = mesh._getInstancesRenderList(subMesh._id);
  53678. if (batch.mustReturn) {
  53679. return;
  53680. }
  53681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53682. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53683. engine.enableEffect(this._effect);
  53684. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53685. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53686. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53687. this._effect.setVector3("lightPosition", this.getLight().position);
  53688. if (scene.activeCamera) {
  53689. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53690. }
  53691. // Alpha test
  53692. if (material && material.needAlphaTesting()) {
  53693. var alphaTexture = material.getAlphaTestTexture();
  53694. if (alphaTexture) {
  53695. this._effect.setTexture("diffuseSampler", alphaTexture);
  53696. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53697. }
  53698. }
  53699. // Bones
  53700. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53701. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53702. }
  53703. if (this.forceBackFacesOnly) {
  53704. engine.setState(true, 0, false, true);
  53705. }
  53706. // Draw
  53707. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53708. if (this.forceBackFacesOnly) {
  53709. engine.setState(true, 0, false, false);
  53710. }
  53711. }
  53712. else {
  53713. // Need to reset refresh rate of the shadowMap
  53714. if (this._shadowMap) {
  53715. this._shadowMap.resetRefreshCounter();
  53716. }
  53717. }
  53718. };
  53719. ShadowGenerator.prototype._applyFilterValues = function () {
  53720. if (!this._shadowMap) {
  53721. return;
  53722. }
  53723. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53724. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53725. }
  53726. else {
  53727. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53728. }
  53729. };
  53730. /**
  53731. * Force shader compilation including textures ready check
  53732. */
  53733. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53734. var _this = this;
  53735. var localOptions = __assign({ useInstances: false }, options);
  53736. var shadowMap = this.getShadowMap();
  53737. if (!shadowMap) {
  53738. if (onCompiled) {
  53739. onCompiled(this);
  53740. }
  53741. return;
  53742. }
  53743. var renderList = shadowMap.renderList;
  53744. if (!renderList) {
  53745. if (onCompiled) {
  53746. onCompiled(this);
  53747. }
  53748. return;
  53749. }
  53750. var subMeshes = new Array();
  53751. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53752. var mesh = renderList_1[_i];
  53753. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53754. }
  53755. if (subMeshes.length === 0) {
  53756. if (onCompiled) {
  53757. onCompiled(this);
  53758. }
  53759. return;
  53760. }
  53761. var currentIndex = 0;
  53762. var checkReady = function () {
  53763. if (!_this._scene || !_this._scene.getEngine()) {
  53764. return;
  53765. }
  53766. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53767. currentIndex++;
  53768. if (currentIndex >= subMeshes.length) {
  53769. if (onCompiled) {
  53770. onCompiled(_this);
  53771. }
  53772. return;
  53773. }
  53774. }
  53775. setTimeout(checkReady, 16);
  53776. };
  53777. checkReady();
  53778. };
  53779. /**
  53780. * Boolean : true when the ShadowGenerator is finally computed.
  53781. */
  53782. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53783. var defines = [];
  53784. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53785. defines.push("#define FLOAT");
  53786. }
  53787. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53788. defines.push("#define ESM");
  53789. }
  53790. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53791. var mesh = subMesh.getMesh();
  53792. var material = subMesh.getMaterial();
  53793. // Alpha test
  53794. if (material && material.needAlphaTesting()) {
  53795. var alphaTexture = material.getAlphaTestTexture();
  53796. if (alphaTexture) {
  53797. defines.push("#define ALPHATEST");
  53798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53799. attribs.push(BABYLON.VertexBuffer.UVKind);
  53800. defines.push("#define UV1");
  53801. }
  53802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53803. if (alphaTexture.coordinatesIndex === 1) {
  53804. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53805. defines.push("#define UV2");
  53806. }
  53807. }
  53808. }
  53809. }
  53810. // Bones
  53811. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53812. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53813. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53814. if (mesh.numBoneInfluencers > 4) {
  53815. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53816. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53817. }
  53818. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53819. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53820. }
  53821. else {
  53822. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53823. }
  53824. // Instances
  53825. if (useInstances) {
  53826. defines.push("#define INSTANCES");
  53827. attribs.push("world0");
  53828. attribs.push("world1");
  53829. attribs.push("world2");
  53830. attribs.push("world3");
  53831. }
  53832. // Get correct effect
  53833. var join = defines.join("\n");
  53834. if (this._cachedDefines !== join) {
  53835. this._cachedDefines = join;
  53836. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53837. }
  53838. return this._effect.isReady();
  53839. };
  53840. /**
  53841. * This creates the defines related to the standard BJS materials.
  53842. */
  53843. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53844. var scene = this._scene;
  53845. var light = this._light;
  53846. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53847. return;
  53848. }
  53849. defines["SHADOW" + lightIndex] = true;
  53850. if (this.usePoissonSampling) {
  53851. defines["SHADOWPCF" + lightIndex] = true;
  53852. }
  53853. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53854. defines["SHADOWESM" + lightIndex] = true;
  53855. }
  53856. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53857. defines["SHADOWCLOSEESM" + lightIndex] = true;
  53858. }
  53859. if (light.needCube()) {
  53860. defines["SHADOWCUBE" + lightIndex] = true;
  53861. }
  53862. };
  53863. /**
  53864. * This binds shadow lights related to the standard BJS materials.
  53865. * It implies the unifroms available on the materials are the standard BJS ones.
  53866. */
  53867. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  53868. var light = this._light;
  53869. var scene = this._scene;
  53870. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53871. return;
  53872. }
  53873. var camera = scene.activeCamera;
  53874. if (!camera) {
  53875. return;
  53876. }
  53877. var shadowMap = this.getShadowMap();
  53878. if (!shadowMap) {
  53879. return;
  53880. }
  53881. if (!light.needCube()) {
  53882. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  53883. }
  53884. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  53885. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  53886. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  53887. };
  53888. // Methods
  53889. /**
  53890. * Returns a Matrix object : the updated transformation matrix.
  53891. */
  53892. ShadowGenerator.prototype.getTransformMatrix = function () {
  53893. var scene = this._scene;
  53894. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  53895. return this._transformMatrix;
  53896. }
  53897. this._currentRenderID = scene.getRenderId();
  53898. this._currentFaceIndexCache = this._currentFaceIndex;
  53899. var lightPosition = this._light.position;
  53900. if (this._light.computeTransformedInformation()) {
  53901. lightPosition = this._light.transformedPosition;
  53902. }
  53903. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  53904. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  53905. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  53906. }
  53907. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  53908. this._cachedPosition = lightPosition.clone();
  53909. this._cachedDirection = this._lightDirection.clone();
  53910. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  53911. var shadowMap = this.getShadowMap();
  53912. if (shadowMap) {
  53913. var renderList = shadowMap.renderList;
  53914. if (renderList) {
  53915. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  53916. }
  53917. }
  53918. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  53919. }
  53920. return this._transformMatrix;
  53921. };
  53922. ShadowGenerator.prototype.recreateShadowMap = function () {
  53923. var shadowMap = this._shadowMap;
  53924. if (!shadowMap) {
  53925. return;
  53926. }
  53927. // Track render list.
  53928. var renderList = shadowMap.renderList;
  53929. // Clean up existing data.
  53930. this._disposeRTTandPostProcesses();
  53931. // Reinitializes.
  53932. this._initializeGenerator();
  53933. // Reaffect the filter to ensure a correct fallback if necessary.
  53934. this.filter = this.filter;
  53935. // Reaffect the filter.
  53936. this._applyFilterValues();
  53937. // Reaffect Render List.
  53938. this._shadowMap.renderList = renderList;
  53939. };
  53940. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  53941. if (this._shadowMap2) {
  53942. this._shadowMap2.dispose();
  53943. this._shadowMap2 = null;
  53944. }
  53945. if (this._downSamplePostprocess) {
  53946. this._downSamplePostprocess.dispose();
  53947. this._downSamplePostprocess = null;
  53948. }
  53949. if (this._boxBlurPostprocess) {
  53950. this._boxBlurPostprocess.dispose();
  53951. this._boxBlurPostprocess = null;
  53952. }
  53953. if (this._kernelBlurXPostprocess) {
  53954. this._kernelBlurXPostprocess.dispose();
  53955. this._kernelBlurXPostprocess = null;
  53956. }
  53957. if (this._kernelBlurYPostprocess) {
  53958. this._kernelBlurYPostprocess.dispose();
  53959. this._kernelBlurYPostprocess = null;
  53960. }
  53961. this._blurPostProcesses = [];
  53962. };
  53963. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  53964. if (this._shadowMap) {
  53965. this._shadowMap.dispose();
  53966. this._shadowMap = null;
  53967. }
  53968. this._disposeBlurPostProcesses();
  53969. };
  53970. /**
  53971. * Disposes the ShadowGenerator.
  53972. * Returns nothing.
  53973. */
  53974. ShadowGenerator.prototype.dispose = function () {
  53975. this._disposeRTTandPostProcesses();
  53976. if (this._light) {
  53977. this._light._shadowGenerator = null;
  53978. this._light._markMeshesAsLightDirty();
  53979. }
  53980. };
  53981. /**
  53982. * Serializes the ShadowGenerator and returns a serializationObject.
  53983. */
  53984. ShadowGenerator.prototype.serialize = function () {
  53985. var serializationObject = {};
  53986. var shadowMap = this.getShadowMap();
  53987. if (!shadowMap) {
  53988. return serializationObject;
  53989. }
  53990. serializationObject.lightId = this._light.id;
  53991. serializationObject.mapSize = shadowMap.getRenderSize();
  53992. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  53993. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  53994. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53995. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53996. serializationObject.usePoissonSampling = this.usePoissonSampling;
  53997. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  53998. serializationObject.depthScale = this.depthScale;
  53999. serializationObject.darkness = this.getDarkness();
  54000. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54001. serializationObject.blurKernel = this.blurKernel;
  54002. serializationObject.blurScale = this.blurScale;
  54003. serializationObject.useKernelBlur = this.useKernelBlur;
  54004. serializationObject.transparencyShadow = this._transparencyShadow;
  54005. serializationObject.renderList = [];
  54006. if (shadowMap.renderList) {
  54007. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54008. var mesh = shadowMap.renderList[meshIndex];
  54009. serializationObject.renderList.push(mesh.id);
  54010. }
  54011. }
  54012. return serializationObject;
  54013. };
  54014. /**
  54015. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54016. */
  54017. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54018. //casting to point light, as light is missing the position attr and typescript complains.
  54019. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54020. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54021. var shadowMap = shadowGenerator.getShadowMap();
  54022. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54023. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54024. meshes.forEach(function (mesh) {
  54025. if (!shadowMap) {
  54026. return;
  54027. }
  54028. if (!shadowMap.renderList) {
  54029. shadowMap.renderList = [];
  54030. }
  54031. shadowMap.renderList.push(mesh);
  54032. });
  54033. }
  54034. if (parsedShadowGenerator.usePoissonSampling) {
  54035. shadowGenerator.usePoissonSampling = true;
  54036. }
  54037. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54038. shadowGenerator.useExponentialShadowMap = true;
  54039. }
  54040. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54041. shadowGenerator.useBlurExponentialShadowMap = true;
  54042. }
  54043. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54044. shadowGenerator.useCloseExponentialShadowMap = true;
  54045. }
  54046. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54047. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54048. }
  54049. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54050. shadowGenerator.useExponentialShadowMap = true;
  54051. }
  54052. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54053. shadowGenerator.useBlurExponentialShadowMap = true;
  54054. }
  54055. if (parsedShadowGenerator.depthScale) {
  54056. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54057. }
  54058. if (parsedShadowGenerator.blurScale) {
  54059. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54060. }
  54061. if (parsedShadowGenerator.blurBoxOffset) {
  54062. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54063. }
  54064. if (parsedShadowGenerator.useKernelBlur) {
  54065. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54066. }
  54067. if (parsedShadowGenerator.blurKernel) {
  54068. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54069. }
  54070. if (parsedShadowGenerator.bias !== undefined) {
  54071. shadowGenerator.bias = parsedShadowGenerator.bias;
  54072. }
  54073. if (parsedShadowGenerator.darkness) {
  54074. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54075. }
  54076. if (parsedShadowGenerator.transparencyShadow) {
  54077. shadowGenerator.setTransparencyShadow(true);
  54078. }
  54079. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54080. return shadowGenerator;
  54081. };
  54082. ShadowGenerator._FILTER_NONE = 0;
  54083. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54084. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54085. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54086. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54087. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54088. return ShadowGenerator;
  54089. }());
  54090. BABYLON.ShadowGenerator = ShadowGenerator;
  54091. })(BABYLON || (BABYLON = {}));
  54092. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54093. var BABYLON;
  54094. (function (BABYLON) {
  54095. var DefaultLoadingScreen = /** @class */ (function () {
  54096. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54097. if (_loadingText === void 0) { _loadingText = ""; }
  54098. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54099. var _this = this;
  54100. this._renderingCanvas = _renderingCanvas;
  54101. this._loadingText = _loadingText;
  54102. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54103. // Resize
  54104. this._resizeLoadingUI = function () {
  54105. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54106. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54107. if (!_this._loadingDiv) {
  54108. return;
  54109. }
  54110. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54111. _this._loadingDiv.style.left = canvasRect.left + "px";
  54112. _this._loadingDiv.style.top = canvasRect.top + "px";
  54113. _this._loadingDiv.style.width = canvasRect.width + "px";
  54114. _this._loadingDiv.style.height = canvasRect.height + "px";
  54115. };
  54116. }
  54117. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54118. if (this._loadingDiv) {
  54119. // Do not add a loading screen if there is already one
  54120. return;
  54121. }
  54122. this._loadingDiv = document.createElement("div");
  54123. this._loadingDiv.id = "babylonjsLoadingDiv";
  54124. this._loadingDiv.style.opacity = "0";
  54125. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54126. this._loadingDiv.style.pointerEvents = "none";
  54127. // Loading text
  54128. this._loadingTextDiv = document.createElement("div");
  54129. this._loadingTextDiv.style.position = "absolute";
  54130. this._loadingTextDiv.style.left = "0";
  54131. this._loadingTextDiv.style.top = "50%";
  54132. this._loadingTextDiv.style.marginTop = "80px";
  54133. this._loadingTextDiv.style.width = "100%";
  54134. this._loadingTextDiv.style.height = "20px";
  54135. this._loadingTextDiv.style.fontFamily = "Arial";
  54136. this._loadingTextDiv.style.fontSize = "14px";
  54137. this._loadingTextDiv.style.color = "white";
  54138. this._loadingTextDiv.style.textAlign = "center";
  54139. this._loadingTextDiv.innerHTML = "Loading";
  54140. this._loadingDiv.appendChild(this._loadingTextDiv);
  54141. //set the predefined text
  54142. this._loadingTextDiv.innerHTML = this._loadingText;
  54143. // Generating keyframes
  54144. var style = document.createElement('style');
  54145. style.type = 'text/css';
  54146. 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 }";
  54147. style.innerHTML = keyFrames;
  54148. document.getElementsByTagName('head')[0].appendChild(style);
  54149. // Loading img
  54150. var imgBack = new Image();
  54151. 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";
  54152. imgBack.style.position = "absolute";
  54153. imgBack.style.left = "50%";
  54154. imgBack.style.top = "50%";
  54155. imgBack.style.marginLeft = "-60px";
  54156. imgBack.style.marginTop = "-60px";
  54157. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54158. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54159. imgBack.style.transformOrigin = "50% 50%";
  54160. imgBack.style.webkitTransformOrigin = "50% 50%";
  54161. this._loadingDiv.appendChild(imgBack);
  54162. this._resizeLoadingUI();
  54163. window.addEventListener("resize", this._resizeLoadingUI);
  54164. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54165. document.body.appendChild(this._loadingDiv);
  54166. this._loadingDiv.style.opacity = "1";
  54167. };
  54168. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54169. var _this = this;
  54170. if (!this._loadingDiv) {
  54171. return;
  54172. }
  54173. var onTransitionEnd = function () {
  54174. if (!_this._loadingDiv) {
  54175. return;
  54176. }
  54177. document.body.removeChild(_this._loadingDiv);
  54178. window.removeEventListener("resize", _this._resizeLoadingUI);
  54179. _this._loadingDiv = null;
  54180. };
  54181. this._loadingDiv.style.opacity = "0";
  54182. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54183. };
  54184. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54185. set: function (text) {
  54186. this._loadingText = text;
  54187. if (this._loadingTextDiv) {
  54188. this._loadingTextDiv.innerHTML = this._loadingText;
  54189. }
  54190. },
  54191. enumerable: true,
  54192. configurable: true
  54193. });
  54194. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54195. get: function () {
  54196. return this._loadingDivBackgroundColor;
  54197. },
  54198. set: function (color) {
  54199. this._loadingDivBackgroundColor = color;
  54200. if (!this._loadingDiv) {
  54201. return;
  54202. }
  54203. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54204. },
  54205. enumerable: true,
  54206. configurable: true
  54207. });
  54208. return DefaultLoadingScreen;
  54209. }());
  54210. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54211. })(BABYLON || (BABYLON = {}));
  54212. //# sourceMappingURL=babylon.loadingScreen.js.map
  54213. var BABYLON;
  54214. (function (BABYLON) {
  54215. var SceneLoaderProgressEvent = /** @class */ (function () {
  54216. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54217. this.lengthComputable = lengthComputable;
  54218. this.loaded = loaded;
  54219. this.total = total;
  54220. }
  54221. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54222. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54223. };
  54224. return SceneLoaderProgressEvent;
  54225. }());
  54226. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54227. var SceneLoader = /** @class */ (function () {
  54228. function SceneLoader() {
  54229. }
  54230. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54231. get: function () {
  54232. return 0;
  54233. },
  54234. enumerable: true,
  54235. configurable: true
  54236. });
  54237. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54238. get: function () {
  54239. return 1;
  54240. },
  54241. enumerable: true,
  54242. configurable: true
  54243. });
  54244. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54245. get: function () {
  54246. return 2;
  54247. },
  54248. enumerable: true,
  54249. configurable: true
  54250. });
  54251. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54252. get: function () {
  54253. return 3;
  54254. },
  54255. enumerable: true,
  54256. configurable: true
  54257. });
  54258. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54259. get: function () {
  54260. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54261. },
  54262. set: function (value) {
  54263. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54264. },
  54265. enumerable: true,
  54266. configurable: true
  54267. });
  54268. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54269. get: function () {
  54270. return SceneLoader._ShowLoadingScreen;
  54271. },
  54272. set: function (value) {
  54273. SceneLoader._ShowLoadingScreen = value;
  54274. },
  54275. enumerable: true,
  54276. configurable: true
  54277. });
  54278. Object.defineProperty(SceneLoader, "loggingLevel", {
  54279. get: function () {
  54280. return SceneLoader._loggingLevel;
  54281. },
  54282. set: function (value) {
  54283. SceneLoader._loggingLevel = value;
  54284. },
  54285. enumerable: true,
  54286. configurable: true
  54287. });
  54288. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54289. get: function () {
  54290. return SceneLoader._CleanBoneMatrixWeights;
  54291. },
  54292. set: function (value) {
  54293. SceneLoader._CleanBoneMatrixWeights = value;
  54294. },
  54295. enumerable: true,
  54296. configurable: true
  54297. });
  54298. SceneLoader._getDefaultPlugin = function () {
  54299. return SceneLoader._registeredPlugins[".babylon"];
  54300. };
  54301. SceneLoader._getPluginForExtension = function (extension) {
  54302. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54303. if (registeredPlugin) {
  54304. return registeredPlugin;
  54305. }
  54306. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54307. return SceneLoader._getDefaultPlugin();
  54308. };
  54309. SceneLoader._getPluginForDirectLoad = function (data) {
  54310. for (var extension in SceneLoader._registeredPlugins) {
  54311. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54312. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54313. return SceneLoader._registeredPlugins[extension];
  54314. }
  54315. }
  54316. return SceneLoader._getDefaultPlugin();
  54317. };
  54318. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54319. if (sceneFilename.name) {
  54320. sceneFilename = sceneFilename.name;
  54321. }
  54322. var queryStringPosition = sceneFilename.indexOf("?");
  54323. if (queryStringPosition !== -1) {
  54324. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54325. }
  54326. var dotPosition = sceneFilename.lastIndexOf(".");
  54327. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54328. return SceneLoader._getPluginForExtension(extension);
  54329. };
  54330. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54331. SceneLoader._getDirectLoad = function (sceneFilename) {
  54332. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54333. return sceneFilename.substr(5);
  54334. }
  54335. return null;
  54336. };
  54337. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54338. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54339. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54340. var plugin;
  54341. if (registeredPlugin.plugin.createPlugin) {
  54342. plugin = registeredPlugin.plugin.createPlugin();
  54343. }
  54344. else {
  54345. plugin = registeredPlugin.plugin;
  54346. }
  54347. var useArrayBuffer = registeredPlugin.isBinary;
  54348. var database;
  54349. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54350. var dataCallback = function (data, responseURL) {
  54351. if (scene.isDisposed) {
  54352. onError("Scene has been disposed");
  54353. return;
  54354. }
  54355. scene.database = database;
  54356. onSuccess(plugin, data, responseURL);
  54357. };
  54358. var request = null;
  54359. var pluginDisposed = false;
  54360. var onDisposeObservable = plugin.onDisposeObservable;
  54361. if (onDisposeObservable) {
  54362. onDisposeObservable.add(function () {
  54363. pluginDisposed = true;
  54364. if (request) {
  54365. request.abort();
  54366. request = null;
  54367. }
  54368. onDispose();
  54369. });
  54370. }
  54371. var manifestChecked = function () {
  54372. if (pluginDisposed) {
  54373. return;
  54374. }
  54375. var url = rootUrl + sceneFilename;
  54376. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54377. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54378. } : undefined, database, useArrayBuffer, function (request, exception) {
  54379. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54380. });
  54381. };
  54382. if (directLoad) {
  54383. dataCallback(directLoad);
  54384. return plugin;
  54385. }
  54386. if (rootUrl.indexOf("file:") === -1) {
  54387. if (scene.getEngine().enableOfflineSupport) {
  54388. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54389. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54390. }
  54391. else {
  54392. manifestChecked();
  54393. }
  54394. }
  54395. else {
  54396. var fileOrString = sceneFilename;
  54397. if (fileOrString.name) {
  54398. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54399. }
  54400. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54401. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54402. }
  54403. else {
  54404. onError("Unable to find file named " + sceneFilename);
  54405. }
  54406. }
  54407. return plugin;
  54408. };
  54409. // Public functions
  54410. SceneLoader.GetPluginForExtension = function (extension) {
  54411. return SceneLoader._getPluginForExtension(extension).plugin;
  54412. };
  54413. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54414. return !!SceneLoader._registeredPlugins[extension];
  54415. };
  54416. SceneLoader.RegisterPlugin = function (plugin) {
  54417. if (typeof plugin.extensions === "string") {
  54418. var extension = plugin.extensions;
  54419. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54420. plugin: plugin,
  54421. isBinary: false
  54422. };
  54423. }
  54424. else {
  54425. var extensions = plugin.extensions;
  54426. Object.keys(extensions).forEach(function (extension) {
  54427. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54428. plugin: plugin,
  54429. isBinary: extensions[extension].isBinary
  54430. };
  54431. });
  54432. }
  54433. };
  54434. /**
  54435. * Import meshes into a scene
  54436. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54437. * @param rootUrl a string that defines the root url for scene and resources
  54438. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54439. * @param scene the instance of BABYLON.Scene to append to
  54440. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54441. * @param onProgress a callback with a progress event for each file being loaded
  54442. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54443. */
  54444. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54445. if (onSuccess === void 0) { onSuccess = null; }
  54446. if (onProgress === void 0) { onProgress = null; }
  54447. if (onError === void 0) { onError = null; }
  54448. if (pluginExtension === void 0) { pluginExtension = null; }
  54449. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54450. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54451. return null;
  54452. }
  54453. var loadingToken = {};
  54454. scene._addPendingData(loadingToken);
  54455. var disposeHandler = function () {
  54456. scene._removePendingData(loadingToken);
  54457. };
  54458. var errorHandler = function (message, exception) {
  54459. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54460. if (onError) {
  54461. onError(scene, errorMessage, exception);
  54462. }
  54463. else {
  54464. BABYLON.Tools.Error(errorMessage);
  54465. // should the exception be thrown?
  54466. }
  54467. disposeHandler();
  54468. };
  54469. var progressHandler = onProgress ? function (event) {
  54470. try {
  54471. onProgress(event);
  54472. }
  54473. catch (e) {
  54474. errorHandler("Error in onProgress callback", e);
  54475. }
  54476. } : undefined;
  54477. var successHandler = function (meshes, particleSystems, skeletons) {
  54478. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54479. if (onSuccess) {
  54480. try {
  54481. onSuccess(meshes, particleSystems, skeletons);
  54482. }
  54483. catch (e) {
  54484. errorHandler("Error in onSuccess callback", e);
  54485. }
  54486. }
  54487. scene._removePendingData(loadingToken);
  54488. };
  54489. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54490. if (plugin.rewriteRootURL) {
  54491. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54492. }
  54493. if (plugin.importMesh) {
  54494. var syncedPlugin = plugin;
  54495. var meshes = new Array();
  54496. var particleSystems = new Array();
  54497. var skeletons = new Array();
  54498. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54499. return;
  54500. }
  54501. scene.loadingPluginName = plugin.name;
  54502. successHandler(meshes, particleSystems, skeletons);
  54503. }
  54504. else {
  54505. var asyncedPlugin = plugin;
  54506. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54507. scene.loadingPluginName = plugin.name;
  54508. successHandler(meshes, particleSystems, skeletons);
  54509. }, progressHandler, errorHandler);
  54510. }
  54511. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54512. };
  54513. /**
  54514. * Load a scene
  54515. * @param rootUrl a string that defines the root url for scene and resources
  54516. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54517. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54518. * @param onSuccess a callback with the scene when import succeeds
  54519. * @param onProgress a callback with a progress event for each file being loaded
  54520. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54521. */
  54522. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54523. if (onSuccess === void 0) { onSuccess = null; }
  54524. if (onProgress === void 0) { onProgress = null; }
  54525. if (onError === void 0) { onError = null; }
  54526. if (pluginExtension === void 0) { pluginExtension = null; }
  54527. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54528. };
  54529. /**
  54530. * Append a scene
  54531. * @param rootUrl a string that defines the root url for scene and resources
  54532. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54533. * @param scene is the instance of BABYLON.Scene to append to
  54534. * @param onSuccess a callback with the scene when import succeeds
  54535. * @param onProgress a callback with a progress event for each file being loaded
  54536. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54537. */
  54538. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54539. if (onSuccess === void 0) { onSuccess = null; }
  54540. if (onProgress === void 0) { onProgress = null; }
  54541. if (onError === void 0) { onError = null; }
  54542. if (pluginExtension === void 0) { pluginExtension = null; }
  54543. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54544. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54545. return null;
  54546. }
  54547. if (SceneLoader.ShowLoadingScreen) {
  54548. scene.getEngine().displayLoadingUI();
  54549. }
  54550. var loadingToken = {};
  54551. scene._addPendingData(loadingToken);
  54552. var disposeHandler = function () {
  54553. scene._removePendingData(loadingToken);
  54554. scene.getEngine().hideLoadingUI();
  54555. };
  54556. var errorHandler = function (message, exception) {
  54557. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54558. if (onError) {
  54559. onError(scene, errorMessage, exception);
  54560. }
  54561. else {
  54562. BABYLON.Tools.Error(errorMessage);
  54563. // should the exception be thrown?
  54564. }
  54565. disposeHandler();
  54566. };
  54567. var progressHandler = onProgress ? function (event) {
  54568. try {
  54569. onProgress(event);
  54570. }
  54571. catch (e) {
  54572. errorHandler("Error in onProgress callback", e);
  54573. }
  54574. } : undefined;
  54575. var successHandler = function () {
  54576. if (onSuccess) {
  54577. try {
  54578. onSuccess(scene);
  54579. }
  54580. catch (e) {
  54581. errorHandler("Error in onSuccess callback", e);
  54582. }
  54583. }
  54584. scene._removePendingData(loadingToken);
  54585. };
  54586. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54587. if (plugin.load) {
  54588. var syncedPlugin = plugin;
  54589. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54590. return;
  54591. }
  54592. scene.loadingPluginName = plugin.name;
  54593. successHandler();
  54594. }
  54595. else {
  54596. var asyncedPlugin = plugin;
  54597. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54598. scene.loadingPluginName = plugin.name;
  54599. successHandler();
  54600. }, progressHandler, errorHandler);
  54601. }
  54602. if (SceneLoader.ShowLoadingScreen) {
  54603. scene.executeWhenReady(function () {
  54604. scene.getEngine().hideLoadingUI();
  54605. });
  54606. }
  54607. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54608. };
  54609. // Flags
  54610. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54611. SceneLoader._ShowLoadingScreen = true;
  54612. SceneLoader._CleanBoneMatrixWeights = false;
  54613. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54614. // Members
  54615. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54616. SceneLoader._registeredPlugins = {};
  54617. return SceneLoader;
  54618. }());
  54619. BABYLON.SceneLoader = SceneLoader;
  54620. ;
  54621. })(BABYLON || (BABYLON = {}));
  54622. //# sourceMappingURL=babylon.sceneLoader.js.map
  54623. var BABYLON;
  54624. (function (BABYLON) {
  54625. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54626. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54627. var parsedMaterial = parsedData.materials[index];
  54628. if (parsedMaterial.id === id) {
  54629. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54630. }
  54631. }
  54632. return null;
  54633. };
  54634. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54635. for (var i in names) {
  54636. if (mesh.name === names[i]) {
  54637. hierarchyIds.push(mesh.id);
  54638. return true;
  54639. }
  54640. }
  54641. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54642. hierarchyIds.push(mesh.id);
  54643. return true;
  54644. }
  54645. return false;
  54646. };
  54647. var logOperation = function (operation, producer) {
  54648. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54649. };
  54650. BABYLON.SceneLoader.RegisterPlugin({
  54651. name: "babylon.js",
  54652. extensions: ".babylon",
  54653. canDirectLoad: function (data) {
  54654. if (data.indexOf("babylon") !== -1) {
  54655. return true;
  54656. }
  54657. return false;
  54658. },
  54659. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  54660. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54661. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54662. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54663. // and avoid problems with multiple concurrent .babylon loads.
  54664. var log = "importMesh has failed JSON parse";
  54665. try {
  54666. var parsedData = JSON.parse(data);
  54667. log = "";
  54668. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54669. if (!meshesNames) {
  54670. meshesNames = null;
  54671. }
  54672. else if (!Array.isArray(meshesNames)) {
  54673. meshesNames = [meshesNames];
  54674. }
  54675. var hierarchyIds = new Array();
  54676. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54677. var loadedSkeletonsIds = [];
  54678. var loadedMaterialsIds = [];
  54679. var index;
  54680. var cache;
  54681. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54682. var parsedMesh = parsedData.meshes[index];
  54683. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  54684. if (meshesNames !== null) {
  54685. // Remove found mesh name from list.
  54686. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  54687. }
  54688. //Geometry?
  54689. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  54690. //does the file contain geometries?
  54691. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  54692. //find the correct geometry and add it to the scene
  54693. var found = false;
  54694. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  54695. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  54696. return;
  54697. }
  54698. else {
  54699. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  54700. if (parsedGeometryData.id === parsedMesh.geometryId) {
  54701. switch (geometryType) {
  54702. case "boxes":
  54703. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  54704. break;
  54705. case "spheres":
  54706. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  54707. break;
  54708. case "cylinders":
  54709. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  54710. break;
  54711. case "toruses":
  54712. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  54713. break;
  54714. case "grounds":
  54715. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  54716. break;
  54717. case "planes":
  54718. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  54719. break;
  54720. case "torusKnots":
  54721. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  54722. break;
  54723. case "vertexData":
  54724. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  54725. break;
  54726. }
  54727. found = true;
  54728. }
  54729. });
  54730. }
  54731. });
  54732. if (found === false) {
  54733. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  54734. }
  54735. }
  54736. }
  54737. // Material ?
  54738. if (parsedMesh.materialId) {
  54739. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  54740. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54741. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  54742. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  54743. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  54744. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  54745. var subMatId = parsedMultiMaterial.materials[matIndex];
  54746. loadedMaterialsIds.push(subMatId);
  54747. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  54748. log += "\n\tMaterial " + mat.toString(fullDetails);
  54749. }
  54750. loadedMaterialsIds.push(parsedMultiMaterial.id);
  54751. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54752. materialFound = true;
  54753. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  54754. break;
  54755. }
  54756. }
  54757. }
  54758. if (materialFound === false) {
  54759. loadedMaterialsIds.push(parsedMesh.materialId);
  54760. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  54761. if (!mat) {
  54762. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  54763. }
  54764. else {
  54765. log += "\n\tMaterial " + mat.toString(fullDetails);
  54766. }
  54767. }
  54768. }
  54769. // Skeleton ?
  54770. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54771. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  54772. if (skeletonAlreadyLoaded === false) {
  54773. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  54774. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  54775. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  54776. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54777. skeletons.push(skeleton);
  54778. loadedSkeletonsIds.push(parsedSkeleton.id);
  54779. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  54780. }
  54781. }
  54782. }
  54783. }
  54784. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54785. meshes.push(mesh);
  54786. log += "\n\tMesh " + mesh.toString(fullDetails);
  54787. }
  54788. }
  54789. // Connecting parents
  54790. var currentMesh;
  54791. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54792. currentMesh = scene.meshes[index];
  54793. if (currentMesh._waitingParentId) {
  54794. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  54795. currentMesh._waitingParentId = null;
  54796. }
  54797. }
  54798. // freeze and compute world matrix application
  54799. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54800. currentMesh = scene.meshes[index];
  54801. if (currentMesh._waitingFreezeWorldMatrix) {
  54802. currentMesh.freezeWorldMatrix();
  54803. currentMesh._waitingFreezeWorldMatrix = null;
  54804. }
  54805. else {
  54806. currentMesh.computeWorldMatrix(true);
  54807. }
  54808. }
  54809. }
  54810. // Particles
  54811. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54812. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54813. var parsedParticleSystem = parsedData.particleSystems[index];
  54814. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  54815. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  54816. }
  54817. }
  54818. }
  54819. return true;
  54820. }
  54821. catch (err) {
  54822. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  54823. if (onError) {
  54824. onError(msg, err);
  54825. }
  54826. else {
  54827. BABYLON.Tools.Log(msg);
  54828. throw err;
  54829. }
  54830. }
  54831. finally {
  54832. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54833. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54834. }
  54835. }
  54836. return false;
  54837. },
  54838. load: function (scene, data, rootUrl, onError) {
  54839. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54840. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54841. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54842. // and avoid problems with multiple concurrent .babylon loads.
  54843. var log = "importScene has failed JSON parse";
  54844. try {
  54845. var parsedData = JSON.parse(data);
  54846. log = "";
  54847. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54848. // Scene
  54849. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  54850. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  54851. }
  54852. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  54853. scene.autoClear = parsedData.autoClear;
  54854. }
  54855. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  54856. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  54857. }
  54858. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  54859. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  54860. }
  54861. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  54862. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  54863. }
  54864. // Fog
  54865. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  54866. scene.fogMode = parsedData.fogMode;
  54867. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  54868. scene.fogStart = parsedData.fogStart;
  54869. scene.fogEnd = parsedData.fogEnd;
  54870. scene.fogDensity = parsedData.fogDensity;
  54871. log += "\tFog mode for scene: ";
  54872. switch (scene.fogMode) {
  54873. // getters not compiling, so using hardcoded
  54874. case 1:
  54875. log += "exp\n";
  54876. break;
  54877. case 2:
  54878. log += "exp2\n";
  54879. break;
  54880. case 3:
  54881. log += "linear\n";
  54882. break;
  54883. }
  54884. }
  54885. //Physics
  54886. if (parsedData.physicsEnabled) {
  54887. var physicsPlugin;
  54888. if (parsedData.physicsEngine === "cannon") {
  54889. physicsPlugin = new BABYLON.CannonJSPlugin();
  54890. }
  54891. else if (parsedData.physicsEngine === "oimo") {
  54892. physicsPlugin = new BABYLON.OimoJSPlugin();
  54893. }
  54894. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  54895. //else - default engine, which is currently oimo
  54896. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  54897. scene.enablePhysics(physicsGravity, physicsPlugin);
  54898. }
  54899. // Metadata
  54900. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  54901. scene.metadata = parsedData.metadata;
  54902. }
  54903. //collisions, if defined. otherwise, default is true
  54904. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  54905. scene.collisionsEnabled = parsedData.collisionsEnabled;
  54906. }
  54907. scene.workerCollisions = !!parsedData.workerCollisions;
  54908. var index;
  54909. var cache;
  54910. // Lights
  54911. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54912. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54913. var parsedLight = parsedData.lights[index];
  54914. var light = BABYLON.Light.Parse(parsedLight, scene);
  54915. if (light) {
  54916. log += (index === 0 ? "\n\tLights:" : "");
  54917. log += "\n\t\t" + light.toString(fullDetails);
  54918. }
  54919. }
  54920. }
  54921. // Animations
  54922. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54923. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54924. var parsedAnimation = parsedData.animations[index];
  54925. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54926. scene.animations.push(animation);
  54927. log += (index === 0 ? "\n\tAnimations:" : "");
  54928. log += "\n\t\t" + animation.toString(fullDetails);
  54929. }
  54930. }
  54931. if (parsedData.autoAnimate) {
  54932. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  54933. }
  54934. // Materials
  54935. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54936. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54937. var parsedMaterial = parsedData.materials[index];
  54938. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54939. log += (index === 0 ? "\n\tMaterials:" : "");
  54940. log += "\n\t\t" + mat.toString(fullDetails);
  54941. }
  54942. }
  54943. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54944. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54945. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54946. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54947. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54948. log += "\n\t\t" + mmat.toString(fullDetails);
  54949. }
  54950. }
  54951. // Morph targets
  54952. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54953. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54954. var managerData = _a[_i];
  54955. BABYLON.MorphTargetManager.Parse(managerData, scene);
  54956. }
  54957. }
  54958. // Skeletons
  54959. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54960. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54961. var parsedSkeleton = parsedData.skeletons[index];
  54962. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54963. log += (index === 0 ? "\n\tSkeletons:" : "");
  54964. log += "\n\t\t" + skeleton.toString(fullDetails);
  54965. }
  54966. }
  54967. // Geometries
  54968. var geometries = parsedData.geometries;
  54969. if (geometries !== undefined && geometries !== null) {
  54970. // Boxes
  54971. var boxes = geometries.boxes;
  54972. if (boxes !== undefined && boxes !== null) {
  54973. for (index = 0, cache = boxes.length; index < cache; index++) {
  54974. var parsedBox = boxes[index];
  54975. BABYLON.BoxGeometry.Parse(parsedBox, scene);
  54976. }
  54977. }
  54978. // Spheres
  54979. var spheres = geometries.spheres;
  54980. if (spheres !== undefined && spheres !== null) {
  54981. for (index = 0, cache = spheres.length; index < cache; index++) {
  54982. var parsedSphere = spheres[index];
  54983. BABYLON.SphereGeometry.Parse(parsedSphere, scene);
  54984. }
  54985. }
  54986. // Cylinders
  54987. var cylinders = geometries.cylinders;
  54988. if (cylinders !== undefined && cylinders !== null) {
  54989. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54990. var parsedCylinder = cylinders[index];
  54991. BABYLON.CylinderGeometry.Parse(parsedCylinder, scene);
  54992. }
  54993. }
  54994. // Toruses
  54995. var toruses = geometries.toruses;
  54996. if (toruses !== undefined && toruses !== null) {
  54997. for (index = 0, cache = toruses.length; index < cache; index++) {
  54998. var parsedTorus = toruses[index];
  54999. BABYLON.TorusGeometry.Parse(parsedTorus, scene);
  55000. }
  55001. }
  55002. // Grounds
  55003. var grounds = geometries.grounds;
  55004. if (grounds !== undefined && grounds !== null) {
  55005. for (index = 0, cache = grounds.length; index < cache; index++) {
  55006. var parsedGround = grounds[index];
  55007. BABYLON.GroundGeometry.Parse(parsedGround, scene);
  55008. }
  55009. }
  55010. // Planes
  55011. var planes = geometries.planes;
  55012. if (planes !== undefined && planes !== null) {
  55013. for (index = 0, cache = planes.length; index < cache; index++) {
  55014. var parsedPlane = planes[index];
  55015. BABYLON.PlaneGeometry.Parse(parsedPlane, scene);
  55016. }
  55017. }
  55018. // TorusKnots
  55019. var torusKnots = geometries.torusKnots;
  55020. if (torusKnots !== undefined && torusKnots !== null) {
  55021. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  55022. var parsedTorusKnot = torusKnots[index];
  55023. BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene);
  55024. }
  55025. }
  55026. // VertexData
  55027. var vertexData = geometries.vertexData;
  55028. if (vertexData !== undefined && vertexData !== null) {
  55029. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55030. var parsedVertexData = vertexData[index];
  55031. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  55032. }
  55033. }
  55034. }
  55035. // Transform nodes
  55036. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55037. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55038. var parsedTransformNode = parsedData.transformNodes[index];
  55039. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55040. }
  55041. }
  55042. // Meshes
  55043. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55044. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55045. var parsedMesh = parsedData.meshes[index];
  55046. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55047. log += (index === 0 ? "\n\tMeshes:" : "");
  55048. log += "\n\t\t" + mesh.toString(fullDetails);
  55049. }
  55050. }
  55051. // Cameras
  55052. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55053. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55054. var parsedCamera = parsedData.cameras[index];
  55055. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55056. log += (index === 0 ? "\n\tCameras:" : "");
  55057. log += "\n\t\t" + camera.toString(fullDetails);
  55058. }
  55059. }
  55060. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55061. scene.setActiveCameraByID(parsedData.activeCameraID);
  55062. }
  55063. // Browsing all the graph to connect the dots
  55064. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55065. var camera = scene.cameras[index];
  55066. if (camera._waitingParentId) {
  55067. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55068. camera._waitingParentId = null;
  55069. }
  55070. }
  55071. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55072. var light_1 = scene.lights[index];
  55073. if (light_1 && light_1._waitingParentId) {
  55074. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55075. light_1._waitingParentId = null;
  55076. }
  55077. }
  55078. // Sounds
  55079. var loadedSounds = [];
  55080. var loadedSound;
  55081. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55082. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55083. var parsedSound = parsedData.sounds[index];
  55084. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55085. if (!parsedSound.url)
  55086. parsedSound.url = parsedSound.name;
  55087. if (!loadedSounds[parsedSound.url]) {
  55088. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55089. loadedSounds[parsedSound.url] = loadedSound;
  55090. }
  55091. else {
  55092. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  55093. }
  55094. }
  55095. else {
  55096. new BABYLON.Sound(parsedSound.name, null, scene);
  55097. }
  55098. }
  55099. }
  55100. loadedSounds = [];
  55101. // Connect parents & children and parse actions
  55102. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55103. var transformNode = scene.transformNodes[index];
  55104. if (transformNode._waitingParentId) {
  55105. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55106. transformNode._waitingParentId = null;
  55107. }
  55108. }
  55109. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55110. var mesh = scene.meshes[index];
  55111. if (mesh._waitingParentId) {
  55112. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55113. mesh._waitingParentId = null;
  55114. }
  55115. if (mesh._waitingActions) {
  55116. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55117. mesh._waitingActions = null;
  55118. }
  55119. }
  55120. // freeze world matrix application
  55121. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55122. var currentMesh = scene.meshes[index];
  55123. if (currentMesh._waitingFreezeWorldMatrix) {
  55124. currentMesh.freezeWorldMatrix();
  55125. currentMesh._waitingFreezeWorldMatrix = null;
  55126. }
  55127. else {
  55128. currentMesh.computeWorldMatrix(true);
  55129. }
  55130. }
  55131. // Particles Systems
  55132. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55133. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55134. var parsedParticleSystem = parsedData.particleSystems[index];
  55135. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55136. }
  55137. }
  55138. // Environment texture
  55139. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55140. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55141. if (parsedData.createDefaultSkybox === true) {
  55142. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55143. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55144. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55145. }
  55146. }
  55147. // Lens flares
  55148. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55149. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55150. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55151. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55152. }
  55153. }
  55154. // Shadows
  55155. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55156. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55157. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55158. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55159. }
  55160. }
  55161. // Lights exclusions / inclusions
  55162. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55163. var light_2 = scene.lights[index];
  55164. // Excluded check
  55165. if (light_2._excludedMeshesIds.length > 0) {
  55166. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55167. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55168. if (excludedMesh) {
  55169. light_2.excludedMeshes.push(excludedMesh);
  55170. }
  55171. }
  55172. light_2._excludedMeshesIds = [];
  55173. }
  55174. // Included check
  55175. if (light_2._includedOnlyMeshesIds.length > 0) {
  55176. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55177. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55178. if (includedOnlyMesh) {
  55179. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55180. }
  55181. }
  55182. light_2._includedOnlyMeshesIds = [];
  55183. }
  55184. }
  55185. // Actions (scene)
  55186. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55187. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55188. }
  55189. // Finish
  55190. return true;
  55191. }
  55192. catch (err) {
  55193. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55194. if (onError) {
  55195. onError(msg, err);
  55196. }
  55197. else {
  55198. BABYLON.Tools.Log(msg);
  55199. throw err;
  55200. }
  55201. }
  55202. finally {
  55203. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55204. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55205. }
  55206. }
  55207. return false;
  55208. }
  55209. });
  55210. })(BABYLON || (BABYLON = {}));
  55211. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55212. var BABYLON;
  55213. (function (BABYLON) {
  55214. var FilesInput = /** @class */ (function () {
  55215. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55216. this.onProcessFileCallback = function () { return true; };
  55217. this._engine = engine;
  55218. this._currentScene = scene;
  55219. this._sceneLoadedCallback = sceneLoadedCallback;
  55220. this._progressCallback = progressCallback;
  55221. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55222. this._textureLoadingCallback = textureLoadingCallback;
  55223. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55224. this._onReloadCallback = onReloadCallback;
  55225. this._errorCallback = errorCallback;
  55226. }
  55227. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55228. var _this = this;
  55229. if (elementToMonitor) {
  55230. this._elementToMonitor = elementToMonitor;
  55231. this._dragEnterHandler = function (e) { _this.drag(e); };
  55232. this._dragOverHandler = function (e) { _this.drag(e); };
  55233. this._dropHandler = function (e) { _this.drop(e); };
  55234. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55235. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55236. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55237. }
  55238. };
  55239. FilesInput.prototype.dispose = function () {
  55240. if (!this._elementToMonitor) {
  55241. return;
  55242. }
  55243. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55244. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55245. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55246. };
  55247. FilesInput.prototype.renderFunction = function () {
  55248. if (this._additionalRenderLoopLogicCallback) {
  55249. this._additionalRenderLoopLogicCallback();
  55250. }
  55251. if (this._currentScene) {
  55252. if (this._textureLoadingCallback) {
  55253. var remaining = this._currentScene.getWaitingItemsCount();
  55254. if (remaining > 0) {
  55255. this._textureLoadingCallback(remaining);
  55256. }
  55257. }
  55258. this._currentScene.render();
  55259. }
  55260. };
  55261. FilesInput.prototype.drag = function (e) {
  55262. e.stopPropagation();
  55263. e.preventDefault();
  55264. };
  55265. FilesInput.prototype.drop = function (eventDrop) {
  55266. eventDrop.stopPropagation();
  55267. eventDrop.preventDefault();
  55268. this.loadFiles(eventDrop);
  55269. };
  55270. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55271. var _this = this;
  55272. var reader = folder.createReader();
  55273. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55274. reader.readEntries(function (entries) {
  55275. remaining.count += entries.length;
  55276. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55277. var entry = entries_1[_i];
  55278. if (entry.isFile) {
  55279. entry.file(function (file) {
  55280. file.correctName = relativePath + file.name;
  55281. files.push(file);
  55282. if (--remaining.count === 0) {
  55283. callback();
  55284. }
  55285. });
  55286. }
  55287. else if (entry.isDirectory) {
  55288. _this._traverseFolder(entry, files, remaining, callback);
  55289. }
  55290. }
  55291. if (--remaining.count) {
  55292. callback();
  55293. }
  55294. });
  55295. };
  55296. FilesInput.prototype._processFiles = function (files) {
  55297. for (var i = 0; i < files.length; i++) {
  55298. var name = files[i].correctName.toLowerCase();
  55299. var extension = name.split('.').pop();
  55300. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55301. continue;
  55302. }
  55303. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55304. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55305. this._sceneFileToLoad = files[i];
  55306. }
  55307. else {
  55308. FilesInput.FilesToLoad[name] = files[i];
  55309. }
  55310. }
  55311. };
  55312. FilesInput.prototype.loadFiles = function (event) {
  55313. var _this = this;
  55314. if (this._startingProcessingFilesCallback)
  55315. this._startingProcessingFilesCallback();
  55316. // Handling data transfer via drag'n'drop
  55317. if (event && event.dataTransfer && event.dataTransfer.files) {
  55318. this._filesToLoad = event.dataTransfer.files;
  55319. }
  55320. // Handling files from input files
  55321. if (event && event.target && event.target.files) {
  55322. this._filesToLoad = event.target.files;
  55323. }
  55324. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55325. var files_1 = new Array();
  55326. var folders = [];
  55327. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55328. for (var i = 0; i < this._filesToLoad.length; i++) {
  55329. var fileToLoad = this._filesToLoad[i];
  55330. var name_1 = fileToLoad.name.toLowerCase();
  55331. var entry = void 0;
  55332. fileToLoad.correctName = name_1;
  55333. if (items) {
  55334. var item = items[i];
  55335. if (item.getAsEntry) {
  55336. entry = item.getAsEntry();
  55337. }
  55338. else if (item.webkitGetAsEntry) {
  55339. entry = item.webkitGetAsEntry();
  55340. }
  55341. }
  55342. if (!entry) {
  55343. files_1.push(fileToLoad);
  55344. }
  55345. else {
  55346. if (entry.isDirectory) {
  55347. folders.push(entry);
  55348. }
  55349. else {
  55350. files_1.push(fileToLoad);
  55351. }
  55352. }
  55353. }
  55354. if (folders.length === 0) {
  55355. this._processFiles(files_1);
  55356. this._processReload();
  55357. }
  55358. else {
  55359. var remaining = { count: folders.length };
  55360. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55361. var folder = folders_1[_i];
  55362. this._traverseFolder(folder, files_1, remaining, function () {
  55363. _this._processFiles(files_1);
  55364. if (remaining.count === 0) {
  55365. _this._processReload();
  55366. }
  55367. });
  55368. }
  55369. }
  55370. }
  55371. };
  55372. FilesInput.prototype._processReload = function () {
  55373. if (this._onReloadCallback) {
  55374. this._onReloadCallback(this._sceneFileToLoad);
  55375. }
  55376. else {
  55377. this.reload();
  55378. }
  55379. };
  55380. FilesInput.prototype.reload = function () {
  55381. var _this = this;
  55382. // If a scene file has been provided
  55383. if (this._sceneFileToLoad) {
  55384. if (this._currentScene) {
  55385. if (BABYLON.Tools.errorsCount > 0) {
  55386. BABYLON.Tools.ClearLogCache();
  55387. }
  55388. this._engine.stopRenderLoop();
  55389. this._currentScene.dispose();
  55390. }
  55391. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55392. _this._currentScene = newScene;
  55393. if (_this._sceneLoadedCallback) {
  55394. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55395. }
  55396. // Wait for textures and shaders to be ready
  55397. _this._currentScene.executeWhenReady(function () {
  55398. _this._engine.runRenderLoop(function () {
  55399. _this.renderFunction();
  55400. });
  55401. });
  55402. }, function (progress) {
  55403. if (_this._progressCallback) {
  55404. _this._progressCallback(progress);
  55405. }
  55406. }, function (scene, message) {
  55407. _this._currentScene = scene;
  55408. if (_this._errorCallback) {
  55409. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55410. }
  55411. });
  55412. }
  55413. else {
  55414. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55415. }
  55416. };
  55417. FilesInput.FilesToLoad = {};
  55418. return FilesInput;
  55419. }());
  55420. BABYLON.FilesInput = FilesInput;
  55421. })(BABYLON || (BABYLON = {}));
  55422. //# sourceMappingURL=babylon.filesInput.js.map
  55423. var BABYLON;
  55424. (function (BABYLON) {
  55425. /**
  55426. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55427. * The underlying implementation relies on an associative array to ensure the best performances.
  55428. * The value can be anything including 'null' but except 'undefined'
  55429. */
  55430. var StringDictionary = /** @class */ (function () {
  55431. function StringDictionary() {
  55432. this._count = 0;
  55433. this._data = {};
  55434. }
  55435. /**
  55436. * This will clear this dictionary and copy the content from the 'source' one.
  55437. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55438. * @param source the dictionary to take the content from and copy to this dictionary
  55439. */
  55440. StringDictionary.prototype.copyFrom = function (source) {
  55441. var _this = this;
  55442. this.clear();
  55443. source.forEach(function (t, v) { return _this.add(t, v); });
  55444. };
  55445. /**
  55446. * Get a value based from its key
  55447. * @param key the given key to get the matching value from
  55448. * @return the value if found, otherwise undefined is returned
  55449. */
  55450. StringDictionary.prototype.get = function (key) {
  55451. var val = this._data[key];
  55452. if (val !== undefined) {
  55453. return val;
  55454. }
  55455. return undefined;
  55456. };
  55457. /**
  55458. * Get a value from its key or add it if it doesn't exist.
  55459. * This method will ensure you that a given key/data will be present in the dictionary.
  55460. * @param key the given key to get the matching value from
  55461. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55462. * The factory will only be invoked if there's no data for the given key.
  55463. * @return the value corresponding to the key.
  55464. */
  55465. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55466. var val = this.get(key);
  55467. if (val !== undefined) {
  55468. return val;
  55469. }
  55470. val = factory(key);
  55471. if (val) {
  55472. this.add(key, val);
  55473. }
  55474. return val;
  55475. };
  55476. /**
  55477. * Get a value from its key if present in the dictionary otherwise add it
  55478. * @param key the key to get the value from
  55479. * @param val if there's no such key/value pair in the dictionary add it with this value
  55480. * @return the value corresponding to the key
  55481. */
  55482. StringDictionary.prototype.getOrAdd = function (key, val) {
  55483. var curVal = this.get(key);
  55484. if (curVal !== undefined) {
  55485. return curVal;
  55486. }
  55487. this.add(key, val);
  55488. return val;
  55489. };
  55490. /**
  55491. * Check if there's a given key in the dictionary
  55492. * @param key the key to check for
  55493. * @return true if the key is present, false otherwise
  55494. */
  55495. StringDictionary.prototype.contains = function (key) {
  55496. return this._data[key] !== undefined;
  55497. };
  55498. /**
  55499. * Add a new key and its corresponding value
  55500. * @param key the key to add
  55501. * @param value the value corresponding to the key
  55502. * @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
  55503. */
  55504. StringDictionary.prototype.add = function (key, value) {
  55505. if (this._data[key] !== undefined) {
  55506. return false;
  55507. }
  55508. this._data[key] = value;
  55509. ++this._count;
  55510. return true;
  55511. };
  55512. StringDictionary.prototype.set = function (key, value) {
  55513. if (this._data[key] === undefined) {
  55514. return false;
  55515. }
  55516. this._data[key] = value;
  55517. return true;
  55518. };
  55519. /**
  55520. * Get the element of the given key and remove it from the dictionary
  55521. * @param key
  55522. */
  55523. StringDictionary.prototype.getAndRemove = function (key) {
  55524. var val = this.get(key);
  55525. if (val !== undefined) {
  55526. delete this._data[key];
  55527. --this._count;
  55528. return val;
  55529. }
  55530. return null;
  55531. };
  55532. /**
  55533. * Remove a key/value from the dictionary.
  55534. * @param key the key to remove
  55535. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55536. */
  55537. StringDictionary.prototype.remove = function (key) {
  55538. if (this.contains(key)) {
  55539. delete this._data[key];
  55540. --this._count;
  55541. return true;
  55542. }
  55543. return false;
  55544. };
  55545. /**
  55546. * Clear the whole content of the dictionary
  55547. */
  55548. StringDictionary.prototype.clear = function () {
  55549. this._data = {};
  55550. this._count = 0;
  55551. };
  55552. Object.defineProperty(StringDictionary.prototype, "count", {
  55553. get: function () {
  55554. return this._count;
  55555. },
  55556. enumerable: true,
  55557. configurable: true
  55558. });
  55559. /**
  55560. * Execute a callback on each key/val of the dictionary.
  55561. * Note that you can remove any element in this dictionary in the callback implementation
  55562. * @param callback the callback to execute on a given key/value pair
  55563. */
  55564. StringDictionary.prototype.forEach = function (callback) {
  55565. for (var cur in this._data) {
  55566. var val = this._data[cur];
  55567. callback(cur, val);
  55568. }
  55569. };
  55570. /**
  55571. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55572. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55573. * Note that you can remove any element in this dictionary in the callback implementation
  55574. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55575. */
  55576. StringDictionary.prototype.first = function (callback) {
  55577. for (var cur in this._data) {
  55578. var val = this._data[cur];
  55579. var res = callback(cur, val);
  55580. if (res) {
  55581. return res;
  55582. }
  55583. }
  55584. return null;
  55585. };
  55586. return StringDictionary;
  55587. }());
  55588. BABYLON.StringDictionary = StringDictionary;
  55589. })(BABYLON || (BABYLON = {}));
  55590. //# sourceMappingURL=babylon.stringDictionary.js.map
  55591. var BABYLON;
  55592. (function (BABYLON) {
  55593. var Tags = /** @class */ (function () {
  55594. function Tags() {
  55595. }
  55596. Tags.EnableFor = function (obj) {
  55597. obj._tags = obj._tags || {};
  55598. obj.hasTags = function () {
  55599. return Tags.HasTags(obj);
  55600. };
  55601. obj.addTags = function (tagsString) {
  55602. return Tags.AddTagsTo(obj, tagsString);
  55603. };
  55604. obj.removeTags = function (tagsString) {
  55605. return Tags.RemoveTagsFrom(obj, tagsString);
  55606. };
  55607. obj.matchesTagsQuery = function (tagsQuery) {
  55608. return Tags.MatchesQuery(obj, tagsQuery);
  55609. };
  55610. };
  55611. Tags.DisableFor = function (obj) {
  55612. delete obj._tags;
  55613. delete obj.hasTags;
  55614. delete obj.addTags;
  55615. delete obj.removeTags;
  55616. delete obj.matchesTagsQuery;
  55617. };
  55618. Tags.HasTags = function (obj) {
  55619. if (!obj._tags) {
  55620. return false;
  55621. }
  55622. return !BABYLON.Tools.IsEmpty(obj._tags);
  55623. };
  55624. Tags.GetTags = function (obj, asString) {
  55625. if (asString === void 0) { asString = true; }
  55626. if (!obj._tags) {
  55627. return null;
  55628. }
  55629. if (asString) {
  55630. var tagsArray = [];
  55631. for (var tag in obj._tags) {
  55632. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55633. tagsArray.push(tag);
  55634. }
  55635. }
  55636. return tagsArray.join(" ");
  55637. }
  55638. else {
  55639. return obj._tags;
  55640. }
  55641. };
  55642. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55643. // a tag cannot start with '||', '&&', and '!'
  55644. // it cannot contain whitespaces
  55645. Tags.AddTagsTo = function (obj, tagsString) {
  55646. if (!tagsString) {
  55647. return;
  55648. }
  55649. if (typeof tagsString !== "string") {
  55650. return;
  55651. }
  55652. var tags = tagsString.split(" ");
  55653. tags.forEach(function (tag, index, array) {
  55654. Tags._AddTagTo(obj, tag);
  55655. });
  55656. };
  55657. Tags._AddTagTo = function (obj, tag) {
  55658. tag = tag.trim();
  55659. if (tag === "" || tag === "true" || tag === "false") {
  55660. return;
  55661. }
  55662. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55663. return;
  55664. }
  55665. Tags.EnableFor(obj);
  55666. obj._tags[tag] = true;
  55667. };
  55668. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55669. if (!Tags.HasTags(obj)) {
  55670. return;
  55671. }
  55672. var tags = tagsString.split(" ");
  55673. for (var t in tags) {
  55674. Tags._RemoveTagFrom(obj, tags[t]);
  55675. }
  55676. };
  55677. Tags._RemoveTagFrom = function (obj, tag) {
  55678. delete obj._tags[tag];
  55679. };
  55680. Tags.MatchesQuery = function (obj, tagsQuery) {
  55681. if (tagsQuery === undefined) {
  55682. return true;
  55683. }
  55684. if (tagsQuery === "") {
  55685. return Tags.HasTags(obj);
  55686. }
  55687. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55688. };
  55689. return Tags;
  55690. }());
  55691. BABYLON.Tags = Tags;
  55692. })(BABYLON || (BABYLON = {}));
  55693. //# sourceMappingURL=babylon.tags.js.map
  55694. var BABYLON;
  55695. (function (BABYLON) {
  55696. var AndOrNotEvaluator = /** @class */ (function () {
  55697. function AndOrNotEvaluator() {
  55698. }
  55699. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  55700. if (!query.match(/\([^\(\)]*\)/g)) {
  55701. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  55702. }
  55703. else {
  55704. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  55705. // remove parenthesis
  55706. r = r.slice(1, r.length - 1);
  55707. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  55708. });
  55709. }
  55710. if (query === "true") {
  55711. return true;
  55712. }
  55713. if (query === "false") {
  55714. return false;
  55715. }
  55716. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  55717. };
  55718. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  55719. evaluateCallback = evaluateCallback || (function (r) {
  55720. return r === "true" ? true : false;
  55721. });
  55722. var result;
  55723. var or = parenthesisContent.split("||");
  55724. for (var i in or) {
  55725. if (or.hasOwnProperty(i)) {
  55726. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  55727. var and = ori.split("&&");
  55728. if (and.length > 1) {
  55729. for (var j = 0; j < and.length; ++j) {
  55730. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  55731. if (andj !== "true" && andj !== "false") {
  55732. if (andj[0] === "!") {
  55733. result = !evaluateCallback(andj.substring(1));
  55734. }
  55735. else {
  55736. result = evaluateCallback(andj);
  55737. }
  55738. }
  55739. else {
  55740. result = andj === "true" ? true : false;
  55741. }
  55742. if (!result) {
  55743. ori = "false";
  55744. break;
  55745. }
  55746. }
  55747. }
  55748. if (result || ori === "true") {
  55749. result = true;
  55750. break;
  55751. }
  55752. // result equals false (or undefined)
  55753. if (ori !== "true" && ori !== "false") {
  55754. if (ori[0] === "!") {
  55755. result = !evaluateCallback(ori.substring(1));
  55756. }
  55757. else {
  55758. result = evaluateCallback(ori);
  55759. }
  55760. }
  55761. else {
  55762. result = ori === "true" ? true : false;
  55763. }
  55764. }
  55765. }
  55766. // the whole parenthesis scope is replaced by 'true' or 'false'
  55767. return result ? "true" : "false";
  55768. };
  55769. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  55770. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  55771. // remove whitespaces
  55772. r = r.replace(/[\s]/g, function () { return ""; });
  55773. return r.length % 2 ? "!" : "";
  55774. });
  55775. booleanString = booleanString.trim();
  55776. if (booleanString === "!true") {
  55777. booleanString = "false";
  55778. }
  55779. else if (booleanString === "!false") {
  55780. booleanString = "true";
  55781. }
  55782. return booleanString;
  55783. };
  55784. return AndOrNotEvaluator;
  55785. }());
  55786. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  55787. })(BABYLON || (BABYLON = {}));
  55788. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  55789. var BABYLON;
  55790. (function (BABYLON) {
  55791. var Database = /** @class */ (function () {
  55792. function Database(urlToScene, callbackManifestChecked) {
  55793. // Handling various flavors of prefixed version of IndexedDB
  55794. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  55795. this.callbackManifestChecked = callbackManifestChecked;
  55796. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  55797. this.db = null;
  55798. this._enableSceneOffline = false;
  55799. this._enableTexturesOffline = false;
  55800. this.manifestVersionFound = 0;
  55801. this.mustUpdateRessources = false;
  55802. this.hasReachedQuota = false;
  55803. if (!Database.IDBStorageEnabled) {
  55804. this.callbackManifestChecked(true);
  55805. }
  55806. else {
  55807. this.checkManifestFile();
  55808. }
  55809. }
  55810. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  55811. get: function () {
  55812. return this._enableSceneOffline;
  55813. },
  55814. enumerable: true,
  55815. configurable: true
  55816. });
  55817. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  55818. get: function () {
  55819. return this._enableTexturesOffline;
  55820. },
  55821. enumerable: true,
  55822. configurable: true
  55823. });
  55824. Database.prototype.checkManifestFile = function () {
  55825. var _this = this;
  55826. var noManifestFile = function () {
  55827. _this._enableSceneOffline = false;
  55828. _this._enableTexturesOffline = false;
  55829. _this.callbackManifestChecked(false);
  55830. };
  55831. var timeStampUsed = false;
  55832. var manifestURL = this.currentSceneUrl + ".manifest";
  55833. var xhr = new XMLHttpRequest();
  55834. if (navigator.onLine) {
  55835. // Adding a timestamp to by-pass browsers' cache
  55836. timeStampUsed = true;
  55837. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  55838. }
  55839. xhr.open("GET", manifestURL, true);
  55840. xhr.addEventListener("load", function () {
  55841. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55842. try {
  55843. var manifestFile = JSON.parse(xhr.response);
  55844. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  55845. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  55846. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  55847. _this.manifestVersionFound = manifestFile.version;
  55848. }
  55849. if (_this.callbackManifestChecked) {
  55850. _this.callbackManifestChecked(true);
  55851. }
  55852. }
  55853. catch (ex) {
  55854. noManifestFile();
  55855. }
  55856. }
  55857. else {
  55858. noManifestFile();
  55859. }
  55860. }, false);
  55861. xhr.addEventListener("error", function (event) {
  55862. if (timeStampUsed) {
  55863. timeStampUsed = false;
  55864. // Let's retry without the timeStamp
  55865. // It could fail when coupled with HTML5 Offline API
  55866. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  55867. xhr.open("GET", retryManifestURL, true);
  55868. xhr.send();
  55869. }
  55870. else {
  55871. noManifestFile();
  55872. }
  55873. }, false);
  55874. try {
  55875. xhr.send();
  55876. }
  55877. catch (ex) {
  55878. BABYLON.Tools.Error("Error on XHR send request.");
  55879. this.callbackManifestChecked(false);
  55880. }
  55881. };
  55882. Database.prototype.openAsync = function (successCallback, errorCallback) {
  55883. var _this = this;
  55884. var handleError = function () {
  55885. _this.isSupported = false;
  55886. if (errorCallback)
  55887. errorCallback();
  55888. };
  55889. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  55890. // Your browser doesn't support IndexedDB
  55891. this.isSupported = false;
  55892. if (errorCallback)
  55893. errorCallback();
  55894. }
  55895. else {
  55896. // If the DB hasn't been opened or created yet
  55897. if (!this.db) {
  55898. this.hasReachedQuota = false;
  55899. this.isSupported = true;
  55900. var request = this.idbFactory.open("babylonjs", 1);
  55901. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  55902. request.onerror = function (event) {
  55903. handleError();
  55904. };
  55905. // executes when a version change transaction cannot complete due to other active transactions
  55906. request.onblocked = function (event) {
  55907. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  55908. handleError();
  55909. };
  55910. // DB has been opened successfully
  55911. request.onsuccess = function (event) {
  55912. _this.db = request.result;
  55913. successCallback();
  55914. };
  55915. // Initialization of the DB. Creating Scenes & Textures stores
  55916. request.onupgradeneeded = function (event) {
  55917. _this.db = (event.target).result;
  55918. if (_this.db) {
  55919. try {
  55920. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  55921. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  55922. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  55923. }
  55924. catch (ex) {
  55925. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  55926. handleError();
  55927. }
  55928. }
  55929. };
  55930. }
  55931. else {
  55932. if (successCallback)
  55933. successCallback();
  55934. }
  55935. }
  55936. };
  55937. Database.prototype.loadImageFromDB = function (url, image) {
  55938. var _this = this;
  55939. var completeURL = Database.ReturnFullUrlLocation(url);
  55940. var saveAndLoadImage = function () {
  55941. if (!_this.hasReachedQuota && _this.db !== null) {
  55942. // the texture is not yet in the DB, let's try to save it
  55943. _this._saveImageIntoDBAsync(completeURL, image);
  55944. }
  55945. else {
  55946. image.src = url;
  55947. }
  55948. };
  55949. if (!this.mustUpdateRessources) {
  55950. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  55951. }
  55952. else {
  55953. saveAndLoadImage();
  55954. }
  55955. };
  55956. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  55957. if (this.isSupported && this.db !== null) {
  55958. var texture;
  55959. var transaction = this.db.transaction(["textures"]);
  55960. transaction.onabort = function (event) {
  55961. image.src = url;
  55962. };
  55963. transaction.oncomplete = function (event) {
  55964. var blobTextureURL;
  55965. if (texture) {
  55966. var URL = window.URL || window.webkitURL;
  55967. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  55968. image.onerror = function () {
  55969. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  55970. image.src = url;
  55971. };
  55972. image.src = blobTextureURL;
  55973. }
  55974. else {
  55975. notInDBCallback();
  55976. }
  55977. };
  55978. var getRequest = transaction.objectStore("textures").get(url);
  55979. getRequest.onsuccess = function (event) {
  55980. texture = (event.target).result;
  55981. };
  55982. getRequest.onerror = function (event) {
  55983. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  55984. image.src = url;
  55985. };
  55986. }
  55987. else {
  55988. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55989. image.src = url;
  55990. }
  55991. };
  55992. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  55993. var _this = this;
  55994. if (this.isSupported) {
  55995. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  55996. var generateBlobUrl = function () {
  55997. var blobTextureURL;
  55998. if (blob) {
  55999. var URL = window.URL || window.webkitURL;
  56000. try {
  56001. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56002. }
  56003. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56004. catch (ex) {
  56005. blobTextureURL = URL.createObjectURL(blob);
  56006. }
  56007. }
  56008. if (blobTextureURL) {
  56009. image.src = blobTextureURL;
  56010. }
  56011. };
  56012. if (Database.IsUASupportingBlobStorage) {
  56013. var xhr = new XMLHttpRequest(), blob;
  56014. xhr.open("GET", url, true);
  56015. xhr.responseType = "blob";
  56016. xhr.addEventListener("load", function () {
  56017. if (xhr.status === 200 && _this.db) {
  56018. // Blob as response (XHR2)
  56019. blob = xhr.response;
  56020. var transaction = _this.db.transaction(["textures"], "readwrite");
  56021. // the transaction could abort because of a QuotaExceededError error
  56022. transaction.onabort = function (event) {
  56023. try {
  56024. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56025. var srcElement = (event.srcElement || event.target);
  56026. var error = srcElement.error;
  56027. if (error && error.name === "QuotaExceededError") {
  56028. _this.hasReachedQuota = true;
  56029. }
  56030. }
  56031. catch (ex) { }
  56032. generateBlobUrl();
  56033. };
  56034. transaction.oncomplete = function (event) {
  56035. generateBlobUrl();
  56036. };
  56037. var newTexture = { textureUrl: url, data: blob };
  56038. try {
  56039. // Put the blob into the dabase
  56040. var addRequest = transaction.objectStore("textures").put(newTexture);
  56041. addRequest.onsuccess = function (event) {
  56042. };
  56043. addRequest.onerror = function (event) {
  56044. generateBlobUrl();
  56045. };
  56046. }
  56047. catch (ex) {
  56048. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56049. if (ex.code === 25) {
  56050. Database.IsUASupportingBlobStorage = false;
  56051. }
  56052. image.src = url;
  56053. }
  56054. }
  56055. else {
  56056. image.src = url;
  56057. }
  56058. }, false);
  56059. xhr.addEventListener("error", function (event) {
  56060. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56061. image.src = url;
  56062. }, false);
  56063. xhr.send();
  56064. }
  56065. else {
  56066. image.src = url;
  56067. }
  56068. }
  56069. else {
  56070. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56071. image.src = url;
  56072. }
  56073. };
  56074. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56075. var _this = this;
  56076. var updateVersion = function () {
  56077. // the version is not yet in the DB or we need to update it
  56078. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56079. };
  56080. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56081. };
  56082. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56083. var _this = this;
  56084. if (this.isSupported && this.db) {
  56085. var version;
  56086. try {
  56087. var transaction = this.db.transaction(["versions"]);
  56088. transaction.oncomplete = function (event) {
  56089. if (version) {
  56090. // If the version in the JSON file is > than the version in DB
  56091. if (_this.manifestVersionFound > version.data) {
  56092. _this.mustUpdateRessources = true;
  56093. updateInDBCallback();
  56094. }
  56095. else {
  56096. callback(version.data);
  56097. }
  56098. }
  56099. else {
  56100. _this.mustUpdateRessources = true;
  56101. updateInDBCallback();
  56102. }
  56103. };
  56104. transaction.onabort = function (event) {
  56105. callback(-1);
  56106. };
  56107. var getRequest = transaction.objectStore("versions").get(url);
  56108. getRequest.onsuccess = function (event) {
  56109. version = (event.target).result;
  56110. };
  56111. getRequest.onerror = function (event) {
  56112. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56113. callback(-1);
  56114. };
  56115. }
  56116. catch (ex) {
  56117. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56118. callback(-1);
  56119. }
  56120. }
  56121. else {
  56122. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56123. callback(-1);
  56124. }
  56125. };
  56126. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56127. var _this = this;
  56128. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56129. try {
  56130. // Open a transaction to the database
  56131. var transaction = this.db.transaction(["versions"], "readwrite");
  56132. // the transaction could abort because of a QuotaExceededError error
  56133. transaction.onabort = function (event) {
  56134. try {
  56135. var error = event.srcElement['error'];
  56136. if (error && error.name === "QuotaExceededError") {
  56137. _this.hasReachedQuota = true;
  56138. }
  56139. }
  56140. catch (ex) { }
  56141. callback(-1);
  56142. };
  56143. transaction.oncomplete = function (event) {
  56144. callback(_this.manifestVersionFound);
  56145. };
  56146. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56147. // Put the scene into the database
  56148. var addRequest = transaction.objectStore("versions").put(newVersion);
  56149. addRequest.onsuccess = function (event) {
  56150. };
  56151. addRequest.onerror = function (event) {
  56152. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56153. };
  56154. }
  56155. catch (ex) {
  56156. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56157. callback(-1);
  56158. }
  56159. }
  56160. else {
  56161. callback(-1);
  56162. }
  56163. };
  56164. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56165. var _this = this;
  56166. var completeUrl = Database.ReturnFullUrlLocation(url);
  56167. var saveAndLoadFile = function () {
  56168. // the scene is not yet in the DB, let's try to save it
  56169. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56170. };
  56171. this._checkVersionFromDB(completeUrl, function (version) {
  56172. if (version !== -1) {
  56173. if (!_this.mustUpdateRessources) {
  56174. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56175. }
  56176. else {
  56177. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56178. }
  56179. }
  56180. else {
  56181. if (errorCallback) {
  56182. errorCallback();
  56183. }
  56184. }
  56185. });
  56186. };
  56187. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56188. if (this.isSupported && this.db) {
  56189. var targetStore;
  56190. if (url.indexOf(".babylon") !== -1) {
  56191. targetStore = "scenes";
  56192. }
  56193. else {
  56194. targetStore = "textures";
  56195. }
  56196. var file;
  56197. var transaction = this.db.transaction([targetStore]);
  56198. transaction.oncomplete = function (event) {
  56199. if (file) {
  56200. callback(file.data);
  56201. }
  56202. else {
  56203. notInDBCallback();
  56204. }
  56205. };
  56206. transaction.onabort = function (event) {
  56207. notInDBCallback();
  56208. };
  56209. var getRequest = transaction.objectStore(targetStore).get(url);
  56210. getRequest.onsuccess = function (event) {
  56211. file = (event.target).result;
  56212. };
  56213. getRequest.onerror = function (event) {
  56214. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56215. notInDBCallback();
  56216. };
  56217. }
  56218. else {
  56219. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56220. callback();
  56221. }
  56222. };
  56223. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56224. var _this = this;
  56225. if (this.isSupported) {
  56226. var targetStore;
  56227. if (url.indexOf(".babylon") !== -1) {
  56228. targetStore = "scenes";
  56229. }
  56230. else {
  56231. targetStore = "textures";
  56232. }
  56233. // Create XHR
  56234. var xhr = new XMLHttpRequest();
  56235. var fileData;
  56236. xhr.open("GET", url, true);
  56237. if (useArrayBuffer) {
  56238. xhr.responseType = "arraybuffer";
  56239. }
  56240. if (progressCallback) {
  56241. xhr.onprogress = progressCallback;
  56242. }
  56243. xhr.addEventListener("load", function () {
  56244. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56245. // Blob as response (XHR2)
  56246. //fileData = xhr.responseText;
  56247. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56248. if (!_this.hasReachedQuota && _this.db) {
  56249. // Open a transaction to the database
  56250. var transaction = _this.db.transaction([targetStore], "readwrite");
  56251. // the transaction could abort because of a QuotaExceededError error
  56252. transaction.onabort = function (event) {
  56253. try {
  56254. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56255. var error = event.srcElement['error'];
  56256. if (error && error.name === "QuotaExceededError") {
  56257. _this.hasReachedQuota = true;
  56258. }
  56259. }
  56260. catch (ex) { }
  56261. callback(fileData);
  56262. };
  56263. transaction.oncomplete = function (event) {
  56264. callback(fileData);
  56265. };
  56266. var newFile;
  56267. if (targetStore === "scenes") {
  56268. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56269. }
  56270. else {
  56271. newFile = { textureUrl: url, data: fileData };
  56272. }
  56273. try {
  56274. // Put the scene into the database
  56275. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56276. addRequest.onsuccess = function (event) {
  56277. };
  56278. addRequest.onerror = function (event) {
  56279. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56280. };
  56281. }
  56282. catch (ex) {
  56283. callback(fileData);
  56284. }
  56285. }
  56286. else {
  56287. callback(fileData);
  56288. }
  56289. }
  56290. else {
  56291. callback();
  56292. }
  56293. }, false);
  56294. xhr.addEventListener("error", function (event) {
  56295. BABYLON.Tools.Error("error on XHR request.");
  56296. callback();
  56297. }, false);
  56298. xhr.send();
  56299. }
  56300. else {
  56301. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56302. callback();
  56303. }
  56304. };
  56305. Database.IsUASupportingBlobStorage = true;
  56306. Database.IDBStorageEnabled = true;
  56307. Database.parseURL = function (url) {
  56308. var a = document.createElement('a');
  56309. a.href = url;
  56310. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56311. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56312. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56313. return absLocation;
  56314. };
  56315. Database.ReturnFullUrlLocation = function (url) {
  56316. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56317. return (Database.parseURL(window.location.href) + url);
  56318. }
  56319. else {
  56320. return url;
  56321. }
  56322. };
  56323. return Database;
  56324. }());
  56325. BABYLON.Database = Database;
  56326. })(BABYLON || (BABYLON = {}));
  56327. //# sourceMappingURL=babylon.database.js.map
  56328. var BABYLON;
  56329. (function (BABYLON) {
  56330. var FresnelParameters = /** @class */ (function () {
  56331. function FresnelParameters() {
  56332. this._isEnabled = true;
  56333. this.leftColor = BABYLON.Color3.White();
  56334. this.rightColor = BABYLON.Color3.Black();
  56335. this.bias = 0;
  56336. this.power = 1;
  56337. }
  56338. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56339. get: function () {
  56340. return this._isEnabled;
  56341. },
  56342. set: function (value) {
  56343. if (this._isEnabled === value) {
  56344. return;
  56345. }
  56346. this._isEnabled = value;
  56347. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56348. },
  56349. enumerable: true,
  56350. configurable: true
  56351. });
  56352. FresnelParameters.prototype.clone = function () {
  56353. var newFresnelParameters = new FresnelParameters();
  56354. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56355. return newFresnelParameters;
  56356. };
  56357. FresnelParameters.prototype.serialize = function () {
  56358. var serializationObject = {};
  56359. serializationObject.isEnabled = this.isEnabled;
  56360. serializationObject.leftColor = this.leftColor;
  56361. serializationObject.rightColor = this.rightColor;
  56362. serializationObject.bias = this.bias;
  56363. serializationObject.power = this.power;
  56364. return serializationObject;
  56365. };
  56366. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56367. var fresnelParameters = new FresnelParameters();
  56368. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56369. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56370. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56371. fresnelParameters.bias = parsedFresnelParameters.bias;
  56372. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56373. return fresnelParameters;
  56374. };
  56375. return FresnelParameters;
  56376. }());
  56377. BABYLON.FresnelParameters = FresnelParameters;
  56378. })(BABYLON || (BABYLON = {}));
  56379. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56380. var BABYLON;
  56381. (function (BABYLON) {
  56382. var MultiMaterial = /** @class */ (function (_super) {
  56383. __extends(MultiMaterial, _super);
  56384. function MultiMaterial(name, scene) {
  56385. var _this = _super.call(this, name, scene, true) || this;
  56386. scene.multiMaterials.push(_this);
  56387. _this.subMaterials = new Array();
  56388. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56389. return _this;
  56390. }
  56391. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56392. get: function () {
  56393. return this._subMaterials;
  56394. },
  56395. set: function (value) {
  56396. this._subMaterials = value;
  56397. this._hookArray(value);
  56398. },
  56399. enumerable: true,
  56400. configurable: true
  56401. });
  56402. MultiMaterial.prototype._hookArray = function (array) {
  56403. var _this = this;
  56404. var oldPush = array.push;
  56405. array.push = function () {
  56406. var items = [];
  56407. for (var _i = 0; _i < arguments.length; _i++) {
  56408. items[_i] = arguments[_i];
  56409. }
  56410. var result = oldPush.apply(array, items);
  56411. _this._markAllSubMeshesAsTexturesDirty();
  56412. return result;
  56413. };
  56414. var oldSplice = array.splice;
  56415. array.splice = function (index, deleteCount) {
  56416. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56417. _this._markAllSubMeshesAsTexturesDirty();
  56418. return deleted;
  56419. };
  56420. };
  56421. // Properties
  56422. MultiMaterial.prototype.getSubMaterial = function (index) {
  56423. if (index < 0 || index >= this.subMaterials.length) {
  56424. return this.getScene().defaultMaterial;
  56425. }
  56426. return this.subMaterials[index];
  56427. };
  56428. MultiMaterial.prototype.getActiveTextures = function () {
  56429. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56430. if (subMaterial) {
  56431. return subMaterial.getActiveTextures();
  56432. }
  56433. else {
  56434. return [];
  56435. }
  56436. }));
  56437. var _a;
  56438. };
  56439. // Methods
  56440. MultiMaterial.prototype.getClassName = function () {
  56441. return "MultiMaterial";
  56442. };
  56443. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56444. for (var index = 0; index < this.subMaterials.length; index++) {
  56445. var subMaterial = this.subMaterials[index];
  56446. if (subMaterial) {
  56447. if (subMaterial.storeEffectOnSubMeshes) {
  56448. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56449. return false;
  56450. }
  56451. continue;
  56452. }
  56453. if (!subMaterial.isReady(mesh)) {
  56454. return false;
  56455. }
  56456. }
  56457. }
  56458. return true;
  56459. };
  56460. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56461. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56462. for (var index = 0; index < this.subMaterials.length; index++) {
  56463. var subMaterial = null;
  56464. var current = this.subMaterials[index];
  56465. if (cloneChildren && current) {
  56466. subMaterial = current.clone(name + "-" + current.name);
  56467. }
  56468. else {
  56469. subMaterial = this.subMaterials[index];
  56470. }
  56471. newMultiMaterial.subMaterials.push(subMaterial);
  56472. }
  56473. return newMultiMaterial;
  56474. };
  56475. MultiMaterial.prototype.serialize = function () {
  56476. var serializationObject = {};
  56477. serializationObject.name = this.name;
  56478. serializationObject.id = this.id;
  56479. if (BABYLON.Tags) {
  56480. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56481. }
  56482. serializationObject.materials = [];
  56483. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56484. var subMat = this.subMaterials[matIndex];
  56485. if (subMat) {
  56486. serializationObject.materials.push(subMat.id);
  56487. }
  56488. else {
  56489. serializationObject.materials.push(null);
  56490. }
  56491. }
  56492. return serializationObject;
  56493. };
  56494. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56495. var scene = this.getScene();
  56496. if (!scene) {
  56497. return;
  56498. }
  56499. var index = scene.multiMaterials.indexOf(this);
  56500. if (index >= 0) {
  56501. scene.multiMaterials.splice(index, 1);
  56502. }
  56503. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56504. };
  56505. return MultiMaterial;
  56506. }(BABYLON.Material));
  56507. BABYLON.MultiMaterial = MultiMaterial;
  56508. })(BABYLON || (BABYLON = {}));
  56509. //# sourceMappingURL=babylon.multiMaterial.js.map
  56510. var BABYLON;
  56511. (function (BABYLON) {
  56512. var FreeCameraTouchInput = /** @class */ (function () {
  56513. function FreeCameraTouchInput() {
  56514. this._offsetX = null;
  56515. this._offsetY = null;
  56516. this._pointerPressed = new Array();
  56517. this.touchAngularSensibility = 200000.0;
  56518. this.touchMoveSensibility = 250.0;
  56519. }
  56520. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56521. var _this = this;
  56522. var previousPosition = null;
  56523. if (this._pointerInput === undefined) {
  56524. this._onLostFocus = function (evt) {
  56525. _this._offsetX = null;
  56526. _this._offsetY = null;
  56527. };
  56528. this._pointerInput = function (p, s) {
  56529. var evt = p.event;
  56530. if (evt.pointerType === "mouse") {
  56531. return;
  56532. }
  56533. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56534. if (!noPreventDefault) {
  56535. evt.preventDefault();
  56536. }
  56537. _this._pointerPressed.push(evt.pointerId);
  56538. if (_this._pointerPressed.length !== 1) {
  56539. return;
  56540. }
  56541. previousPosition = {
  56542. x: evt.clientX,
  56543. y: evt.clientY
  56544. };
  56545. }
  56546. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56547. if (!noPreventDefault) {
  56548. evt.preventDefault();
  56549. }
  56550. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56551. if (index === -1) {
  56552. return;
  56553. }
  56554. _this._pointerPressed.splice(index, 1);
  56555. if (index != 0) {
  56556. return;
  56557. }
  56558. previousPosition = null;
  56559. _this._offsetX = null;
  56560. _this._offsetY = null;
  56561. }
  56562. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56563. if (!noPreventDefault) {
  56564. evt.preventDefault();
  56565. }
  56566. if (!previousPosition) {
  56567. return;
  56568. }
  56569. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56570. if (index != 0) {
  56571. return;
  56572. }
  56573. _this._offsetX = evt.clientX - previousPosition.x;
  56574. _this._offsetY = -(evt.clientY - previousPosition.y);
  56575. }
  56576. };
  56577. }
  56578. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56579. if (this._onLostFocus) {
  56580. element.addEventListener("blur", this._onLostFocus);
  56581. }
  56582. };
  56583. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56584. if (this._pointerInput && element) {
  56585. if (this._observer) {
  56586. this.camera.getScene().onPointerObservable.remove(this._observer);
  56587. this._observer = null;
  56588. }
  56589. if (this._onLostFocus) {
  56590. element.removeEventListener("blur", this._onLostFocus);
  56591. this._onLostFocus = null;
  56592. }
  56593. this._pointerPressed = [];
  56594. this._offsetX = null;
  56595. this._offsetY = null;
  56596. }
  56597. };
  56598. FreeCameraTouchInput.prototype.checkInputs = function () {
  56599. if (this._offsetX && this._offsetY) {
  56600. var camera = this.camera;
  56601. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56602. if (this._pointerPressed.length > 1) {
  56603. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56604. }
  56605. else {
  56606. var speed = camera._computeLocalCameraSpeed();
  56607. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56608. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56609. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56610. }
  56611. }
  56612. };
  56613. FreeCameraTouchInput.prototype.getClassName = function () {
  56614. return "FreeCameraTouchInput";
  56615. };
  56616. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56617. return "touch";
  56618. };
  56619. __decorate([
  56620. BABYLON.serialize()
  56621. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56622. __decorate([
  56623. BABYLON.serialize()
  56624. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56625. return FreeCameraTouchInput;
  56626. }());
  56627. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56628. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56629. })(BABYLON || (BABYLON = {}));
  56630. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56631. var BABYLON;
  56632. (function (BABYLON) {
  56633. // We're mainly based on the logic defined into the FreeCamera code
  56634. var TouchCamera = /** @class */ (function (_super) {
  56635. __extends(TouchCamera, _super);
  56636. //-- end properties for backward compatibility for inputs
  56637. function TouchCamera(name, position, scene) {
  56638. var _this = _super.call(this, name, position, scene) || this;
  56639. _this.inputs.addTouch();
  56640. _this._setupInputs();
  56641. return _this;
  56642. }
  56643. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56644. //-- Begin properties for backward compatibility for inputs
  56645. get: function () {
  56646. var touch = this.inputs.attached["touch"];
  56647. if (touch)
  56648. return touch.touchAngularSensibility;
  56649. return 0;
  56650. },
  56651. set: function (value) {
  56652. var touch = this.inputs.attached["touch"];
  56653. if (touch)
  56654. touch.touchAngularSensibility = value;
  56655. },
  56656. enumerable: true,
  56657. configurable: true
  56658. });
  56659. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56660. get: function () {
  56661. var touch = this.inputs.attached["touch"];
  56662. if (touch)
  56663. return touch.touchMoveSensibility;
  56664. return 0;
  56665. },
  56666. set: function (value) {
  56667. var touch = this.inputs.attached["touch"];
  56668. if (touch)
  56669. touch.touchMoveSensibility = value;
  56670. },
  56671. enumerable: true,
  56672. configurable: true
  56673. });
  56674. TouchCamera.prototype.getClassName = function () {
  56675. return "TouchCamera";
  56676. };
  56677. TouchCamera.prototype._setupInputs = function () {
  56678. var mouse = this.inputs.attached["mouse"];
  56679. if (mouse) {
  56680. mouse.touchEnabled = false;
  56681. }
  56682. };
  56683. return TouchCamera;
  56684. }(BABYLON.FreeCamera));
  56685. BABYLON.TouchCamera = TouchCamera;
  56686. })(BABYLON || (BABYLON = {}));
  56687. //# sourceMappingURL=babylon.touchCamera.js.map
  56688. var BABYLON;
  56689. (function (BABYLON) {
  56690. var ProceduralTexture = /** @class */ (function (_super) {
  56691. __extends(ProceduralTexture, _super);
  56692. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56693. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56694. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56695. if (isCube === void 0) { isCube = false; }
  56696. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56697. _this.isCube = isCube;
  56698. _this.isEnabled = true;
  56699. _this._currentRefreshId = -1;
  56700. _this._refreshRate = 1;
  56701. _this._vertexBuffers = {};
  56702. _this._uniforms = new Array();
  56703. _this._samplers = new Array();
  56704. _this._textures = {};
  56705. _this._floats = {};
  56706. _this._floatsArrays = {};
  56707. _this._colors3 = {};
  56708. _this._colors4 = {};
  56709. _this._vectors2 = {};
  56710. _this._vectors3 = {};
  56711. _this._matrices = {};
  56712. _this._fallbackTextureUsed = false;
  56713. scene._proceduralTextures.push(_this);
  56714. _this._engine = scene.getEngine();
  56715. _this.name = name;
  56716. _this.isRenderTarget = true;
  56717. _this._size = size;
  56718. _this._generateMipMaps = generateMipMaps;
  56719. _this.setFragment(fragment);
  56720. _this._fallbackTexture = fallbackTexture;
  56721. if (isCube) {
  56722. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  56723. _this.setFloat("face", 0);
  56724. }
  56725. else {
  56726. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  56727. }
  56728. // VBO
  56729. var vertices = [];
  56730. vertices.push(1, 1);
  56731. vertices.push(-1, 1);
  56732. vertices.push(-1, -1);
  56733. vertices.push(1, -1);
  56734. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  56735. _this._createIndexBuffer();
  56736. return _this;
  56737. }
  56738. ProceduralTexture.prototype._createIndexBuffer = function () {
  56739. var engine = this._engine;
  56740. // Indices
  56741. var indices = [];
  56742. indices.push(0);
  56743. indices.push(1);
  56744. indices.push(2);
  56745. indices.push(0);
  56746. indices.push(2);
  56747. indices.push(3);
  56748. this._indexBuffer = engine.createIndexBuffer(indices);
  56749. };
  56750. ProceduralTexture.prototype._rebuild = function () {
  56751. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56752. if (vb) {
  56753. vb._rebuild();
  56754. }
  56755. this._createIndexBuffer();
  56756. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56757. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56758. }
  56759. };
  56760. ProceduralTexture.prototype.reset = function () {
  56761. if (this._effect === undefined) {
  56762. return;
  56763. }
  56764. var engine = this._engine;
  56765. engine._releaseEffect(this._effect);
  56766. };
  56767. ProceduralTexture.prototype.isReady = function () {
  56768. var _this = this;
  56769. var engine = this._engine;
  56770. var shaders;
  56771. if (!this._fragment) {
  56772. return false;
  56773. }
  56774. if (this._fallbackTextureUsed) {
  56775. return true;
  56776. }
  56777. if (this._fragment.fragmentElement !== undefined) {
  56778. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  56779. }
  56780. else {
  56781. shaders = { vertex: "procedural", fragment: this._fragment };
  56782. }
  56783. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  56784. _this.releaseInternalTexture();
  56785. if (_this._fallbackTexture) {
  56786. _this._texture = _this._fallbackTexture._texture;
  56787. if (_this._texture) {
  56788. _this._texture.incrementReferences();
  56789. }
  56790. }
  56791. _this._fallbackTextureUsed = true;
  56792. });
  56793. return this._effect.isReady();
  56794. };
  56795. ProceduralTexture.prototype.resetRefreshCounter = function () {
  56796. this._currentRefreshId = -1;
  56797. };
  56798. ProceduralTexture.prototype.setFragment = function (fragment) {
  56799. this._fragment = fragment;
  56800. };
  56801. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  56802. get: function () {
  56803. return this._refreshRate;
  56804. },
  56805. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56806. set: function (value) {
  56807. this._refreshRate = value;
  56808. this.resetRefreshCounter();
  56809. },
  56810. enumerable: true,
  56811. configurable: true
  56812. });
  56813. ProceduralTexture.prototype._shouldRender = function () {
  56814. if (!this.isEnabled || !this.isReady() || !this._texture) {
  56815. return false;
  56816. }
  56817. if (this._fallbackTextureUsed) {
  56818. return false;
  56819. }
  56820. if (this._currentRefreshId === -1) {
  56821. this._currentRefreshId = 1;
  56822. return true;
  56823. }
  56824. if (this.refreshRate === this._currentRefreshId) {
  56825. this._currentRefreshId = 1;
  56826. return true;
  56827. }
  56828. this._currentRefreshId++;
  56829. return false;
  56830. };
  56831. ProceduralTexture.prototype.getRenderSize = function () {
  56832. return this._size;
  56833. };
  56834. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  56835. if (this._fallbackTextureUsed) {
  56836. return;
  56837. }
  56838. this.releaseInternalTexture();
  56839. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  56840. };
  56841. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  56842. if (this._uniforms.indexOf(uniformName) === -1) {
  56843. this._uniforms.push(uniformName);
  56844. }
  56845. };
  56846. ProceduralTexture.prototype.setTexture = function (name, texture) {
  56847. if (this._samplers.indexOf(name) === -1) {
  56848. this._samplers.push(name);
  56849. }
  56850. this._textures[name] = texture;
  56851. return this;
  56852. };
  56853. ProceduralTexture.prototype.setFloat = function (name, value) {
  56854. this._checkUniform(name);
  56855. this._floats[name] = value;
  56856. return this;
  56857. };
  56858. ProceduralTexture.prototype.setFloats = function (name, value) {
  56859. this._checkUniform(name);
  56860. this._floatsArrays[name] = value;
  56861. return this;
  56862. };
  56863. ProceduralTexture.prototype.setColor3 = function (name, value) {
  56864. this._checkUniform(name);
  56865. this._colors3[name] = value;
  56866. return this;
  56867. };
  56868. ProceduralTexture.prototype.setColor4 = function (name, value) {
  56869. this._checkUniform(name);
  56870. this._colors4[name] = value;
  56871. return this;
  56872. };
  56873. ProceduralTexture.prototype.setVector2 = function (name, value) {
  56874. this._checkUniform(name);
  56875. this._vectors2[name] = value;
  56876. return this;
  56877. };
  56878. ProceduralTexture.prototype.setVector3 = function (name, value) {
  56879. this._checkUniform(name);
  56880. this._vectors3[name] = value;
  56881. return this;
  56882. };
  56883. ProceduralTexture.prototype.setMatrix = function (name, value) {
  56884. this._checkUniform(name);
  56885. this._matrices[name] = value;
  56886. return this;
  56887. };
  56888. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56889. var scene = this.getScene();
  56890. if (!scene) {
  56891. return;
  56892. }
  56893. var engine = this._engine;
  56894. // Render
  56895. engine.enableEffect(this._effect);
  56896. engine.setState(false);
  56897. // Texture
  56898. for (var name in this._textures) {
  56899. this._effect.setTexture(name, this._textures[name]);
  56900. }
  56901. // Float
  56902. for (name in this._floats) {
  56903. this._effect.setFloat(name, this._floats[name]);
  56904. }
  56905. // Floats
  56906. for (name in this._floatsArrays) {
  56907. this._effect.setArray(name, this._floatsArrays[name]);
  56908. }
  56909. // Color3
  56910. for (name in this._colors3) {
  56911. this._effect.setColor3(name, this._colors3[name]);
  56912. }
  56913. // Color4
  56914. for (name in this._colors4) {
  56915. var color = this._colors4[name];
  56916. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56917. }
  56918. // Vector2
  56919. for (name in this._vectors2) {
  56920. this._effect.setVector2(name, this._vectors2[name]);
  56921. }
  56922. // Vector3
  56923. for (name in this._vectors3) {
  56924. this._effect.setVector3(name, this._vectors3[name]);
  56925. }
  56926. // Matrix
  56927. for (name in this._matrices) {
  56928. this._effect.setMatrix(name, this._matrices[name]);
  56929. }
  56930. if (!this._texture) {
  56931. return;
  56932. }
  56933. if (this.isCube) {
  56934. for (var face = 0; face < 6; face++) {
  56935. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  56936. // VBOs
  56937. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56938. this._effect.setFloat("face", face);
  56939. // Clear
  56940. engine.clear(scene.clearColor, true, true, true);
  56941. // Draw order
  56942. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56943. // Mipmaps
  56944. if (face === 5) {
  56945. engine.generateMipMapsForCubemap(this._texture);
  56946. }
  56947. }
  56948. }
  56949. else {
  56950. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  56951. // VBOs
  56952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56953. // Clear
  56954. engine.clear(scene.clearColor, true, true, true);
  56955. // Draw order
  56956. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56957. }
  56958. // Unbind
  56959. engine.unBindFramebuffer(this._texture, this.isCube);
  56960. if (this.onGenerated) {
  56961. this.onGenerated();
  56962. }
  56963. };
  56964. ProceduralTexture.prototype.clone = function () {
  56965. var textureSize = this.getSize();
  56966. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  56967. // Base texture
  56968. newTexture.hasAlpha = this.hasAlpha;
  56969. newTexture.level = this.level;
  56970. // RenderTarget Texture
  56971. newTexture.coordinatesMode = this.coordinatesMode;
  56972. return newTexture;
  56973. };
  56974. ProceduralTexture.prototype.dispose = function () {
  56975. var scene = this.getScene();
  56976. if (!scene) {
  56977. return;
  56978. }
  56979. var index = scene._proceduralTextures.indexOf(this);
  56980. if (index >= 0) {
  56981. scene._proceduralTextures.splice(index, 1);
  56982. }
  56983. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56984. if (vertexBuffer) {
  56985. vertexBuffer.dispose();
  56986. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56987. }
  56988. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  56989. this._indexBuffer = null;
  56990. }
  56991. _super.prototype.dispose.call(this);
  56992. };
  56993. return ProceduralTexture;
  56994. }(BABYLON.Texture));
  56995. BABYLON.ProceduralTexture = ProceduralTexture;
  56996. })(BABYLON || (BABYLON = {}));
  56997. //# sourceMappingURL=babylon.proceduralTexture.js.map
  56998. var BABYLON;
  56999. (function (BABYLON) {
  57000. var CustomProceduralTexture = /** @class */ (function (_super) {
  57001. __extends(CustomProceduralTexture, _super);
  57002. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57003. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57004. _this._animate = true;
  57005. _this._time = 0;
  57006. _this._texturePath = texturePath;
  57007. //Try to load json
  57008. _this.loadJson(texturePath);
  57009. _this.refreshRate = 1;
  57010. return _this;
  57011. }
  57012. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57013. var _this = this;
  57014. var noConfigFile = function () {
  57015. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57016. try {
  57017. _this.setFragment(_this._texturePath);
  57018. }
  57019. catch (ex) {
  57020. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57021. }
  57022. };
  57023. var configFileUrl = jsonUrl + "/config.json";
  57024. var xhr = new XMLHttpRequest();
  57025. xhr.open("GET", configFileUrl, true);
  57026. xhr.addEventListener("load", function () {
  57027. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57028. try {
  57029. _this._config = JSON.parse(xhr.response);
  57030. _this.updateShaderUniforms();
  57031. _this.updateTextures();
  57032. _this.setFragment(_this._texturePath + "/custom");
  57033. _this._animate = _this._config.animate;
  57034. _this.refreshRate = _this._config.refreshrate;
  57035. }
  57036. catch (ex) {
  57037. noConfigFile();
  57038. }
  57039. }
  57040. else {
  57041. noConfigFile();
  57042. }
  57043. }, false);
  57044. xhr.addEventListener("error", function () {
  57045. noConfigFile();
  57046. }, false);
  57047. try {
  57048. xhr.send();
  57049. }
  57050. catch (ex) {
  57051. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57052. }
  57053. };
  57054. CustomProceduralTexture.prototype.isReady = function () {
  57055. if (!_super.prototype.isReady.call(this)) {
  57056. return false;
  57057. }
  57058. for (var name in this._textures) {
  57059. var texture = this._textures[name];
  57060. if (!texture.isReady()) {
  57061. return false;
  57062. }
  57063. }
  57064. return true;
  57065. };
  57066. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57067. var scene = this.getScene();
  57068. if (this._animate && scene) {
  57069. this._time += scene.getAnimationRatio() * 0.03;
  57070. this.updateShaderUniforms();
  57071. }
  57072. _super.prototype.render.call(this, useCameraPostProcess);
  57073. };
  57074. CustomProceduralTexture.prototype.updateTextures = function () {
  57075. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57076. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57077. }
  57078. };
  57079. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57080. if (this._config) {
  57081. for (var j = 0; j < this._config.uniforms.length; j++) {
  57082. var uniform = this._config.uniforms[j];
  57083. switch (uniform.type) {
  57084. case "float":
  57085. this.setFloat(uniform.name, uniform.value);
  57086. break;
  57087. case "color3":
  57088. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57089. break;
  57090. case "color4":
  57091. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57092. break;
  57093. case "vector2":
  57094. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57095. break;
  57096. case "vector3":
  57097. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57098. break;
  57099. }
  57100. }
  57101. }
  57102. this.setFloat("time", this._time);
  57103. };
  57104. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57105. get: function () {
  57106. return this._animate;
  57107. },
  57108. set: function (value) {
  57109. this._animate = value;
  57110. },
  57111. enumerable: true,
  57112. configurable: true
  57113. });
  57114. return CustomProceduralTexture;
  57115. }(BABYLON.ProceduralTexture));
  57116. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57117. })(BABYLON || (BABYLON = {}));
  57118. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57119. var BABYLON;
  57120. (function (BABYLON) {
  57121. var FreeCameraGamepadInput = /** @class */ (function () {
  57122. function FreeCameraGamepadInput() {
  57123. this.gamepadAngularSensibility = 200;
  57124. this.gamepadMoveSensibility = 40;
  57125. // private members
  57126. this._cameraTransform = BABYLON.Matrix.Identity();
  57127. this._deltaTransform = BABYLON.Vector3.Zero();
  57128. this._vector3 = BABYLON.Vector3.Zero();
  57129. this._vector2 = BABYLON.Vector2.Zero();
  57130. }
  57131. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57132. var _this = this;
  57133. var manager = this.camera.getScene().gamepadManager;
  57134. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57135. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57136. // prioritize XBOX gamepads.
  57137. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57138. _this.gamepad = gamepad;
  57139. }
  57140. }
  57141. });
  57142. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57143. if (_this.gamepad === gamepad) {
  57144. _this.gamepad = null;
  57145. }
  57146. });
  57147. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57148. };
  57149. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57150. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57151. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57152. this.gamepad = null;
  57153. };
  57154. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57155. if (this.gamepad && this.gamepad.leftStick) {
  57156. var camera = this.camera;
  57157. var LSValues = this.gamepad.leftStick;
  57158. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57159. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57160. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57161. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57162. var RSValues = this.gamepad.rightStick;
  57163. if (RSValues) {
  57164. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57165. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57166. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57167. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57168. }
  57169. else {
  57170. RSValues = { x: 0, y: 0 };
  57171. }
  57172. if (!camera.rotationQuaternion) {
  57173. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57174. }
  57175. else {
  57176. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57177. }
  57178. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57179. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57180. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57181. camera.cameraDirection.addInPlace(this._deltaTransform);
  57182. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57183. camera.cameraRotation.addInPlace(this._vector2);
  57184. }
  57185. };
  57186. FreeCameraGamepadInput.prototype.getClassName = function () {
  57187. return "FreeCameraGamepadInput";
  57188. };
  57189. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57190. return "gamepad";
  57191. };
  57192. __decorate([
  57193. BABYLON.serialize()
  57194. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57195. __decorate([
  57196. BABYLON.serialize()
  57197. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57198. return FreeCameraGamepadInput;
  57199. }());
  57200. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57201. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57202. })(BABYLON || (BABYLON = {}));
  57203. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57204. var BABYLON;
  57205. (function (BABYLON) {
  57206. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57207. function ArcRotateCameraGamepadInput() {
  57208. this.gamepadRotationSensibility = 80;
  57209. this.gamepadMoveSensibility = 40;
  57210. }
  57211. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57212. var _this = this;
  57213. var manager = this.camera.getScene().gamepadManager;
  57214. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57215. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57216. // prioritize XBOX gamepads.
  57217. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57218. _this.gamepad = gamepad;
  57219. }
  57220. }
  57221. });
  57222. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57223. if (_this.gamepad === gamepad) {
  57224. _this.gamepad = null;
  57225. }
  57226. });
  57227. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57228. };
  57229. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57230. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57231. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57232. this.gamepad = null;
  57233. };
  57234. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57235. if (this.gamepad) {
  57236. var camera = this.camera;
  57237. var RSValues = this.gamepad.rightStick;
  57238. if (RSValues) {
  57239. if (RSValues.x != 0) {
  57240. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57241. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57242. camera.inertialAlphaOffset += normalizedRX;
  57243. }
  57244. }
  57245. if (RSValues.y != 0) {
  57246. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57247. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57248. camera.inertialBetaOffset += normalizedRY;
  57249. }
  57250. }
  57251. }
  57252. var LSValues = this.gamepad.leftStick;
  57253. if (LSValues && LSValues.y != 0) {
  57254. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57255. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57256. this.camera.inertialRadiusOffset -= normalizedLY;
  57257. }
  57258. }
  57259. }
  57260. };
  57261. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57262. return "ArcRotateCameraGamepadInput";
  57263. };
  57264. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57265. return "gamepad";
  57266. };
  57267. __decorate([
  57268. BABYLON.serialize()
  57269. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57270. __decorate([
  57271. BABYLON.serialize()
  57272. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57273. return ArcRotateCameraGamepadInput;
  57274. }());
  57275. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57276. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57277. })(BABYLON || (BABYLON = {}));
  57278. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57279. var BABYLON;
  57280. (function (BABYLON) {
  57281. var GamepadManager = /** @class */ (function () {
  57282. function GamepadManager(_scene) {
  57283. var _this = this;
  57284. this._scene = _scene;
  57285. this._babylonGamepads = [];
  57286. this._oneGamepadConnected = false;
  57287. this._isMonitoring = false;
  57288. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57289. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57290. this._gamepadEventSupported = false;
  57291. }
  57292. else {
  57293. this._gamepadEventSupported = 'GamepadEvent' in window;
  57294. this._gamepadSupport = (navigator.getGamepads ||
  57295. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57296. }
  57297. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57298. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57299. for (var i in _this._babylonGamepads) {
  57300. var gamepad = _this._babylonGamepads[i];
  57301. if (gamepad && gamepad._isConnected) {
  57302. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57303. }
  57304. }
  57305. });
  57306. this._onGamepadConnectedEvent = function (evt) {
  57307. var gamepad = evt.gamepad;
  57308. if (gamepad.index in _this._babylonGamepads) {
  57309. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57310. return;
  57311. }
  57312. }
  57313. var newGamepad;
  57314. if (_this._babylonGamepads[gamepad.index]) {
  57315. newGamepad = _this._babylonGamepads[gamepad.index];
  57316. newGamepad.browserGamepad = gamepad;
  57317. newGamepad._isConnected = true;
  57318. }
  57319. else {
  57320. newGamepad = _this._addNewGamepad(gamepad);
  57321. }
  57322. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57323. _this._startMonitoringGamepads();
  57324. };
  57325. this._onGamepadDisconnectedEvent = function (evt) {
  57326. var gamepad = evt.gamepad;
  57327. // Remove the gamepad from the list of gamepads to monitor.
  57328. for (var i in _this._babylonGamepads) {
  57329. if (_this._babylonGamepads[i].index === gamepad.index) {
  57330. var disconnectedGamepad = _this._babylonGamepads[i];
  57331. disconnectedGamepad._isConnected = false;
  57332. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57333. break;
  57334. }
  57335. }
  57336. };
  57337. if (this._gamepadSupport) {
  57338. //first add already-connected gamepads
  57339. this._updateGamepadObjects();
  57340. if (this._babylonGamepads.length) {
  57341. this._startMonitoringGamepads();
  57342. }
  57343. // Checking if the gamepad connected event is supported (like in Firefox)
  57344. if (this._gamepadEventSupported) {
  57345. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57346. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57347. }
  57348. else {
  57349. this._startMonitoringGamepads();
  57350. }
  57351. }
  57352. }
  57353. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57354. get: function () {
  57355. return this._babylonGamepads;
  57356. },
  57357. enumerable: true,
  57358. configurable: true
  57359. });
  57360. GamepadManager.prototype.getGamepadByType = function (type) {
  57361. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57362. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57363. var gamepad = _a[_i];
  57364. if (gamepad && gamepad.type === type) {
  57365. return gamepad;
  57366. }
  57367. }
  57368. return null;
  57369. };
  57370. GamepadManager.prototype.dispose = function () {
  57371. if (this._gamepadEventSupported) {
  57372. if (this._onGamepadConnectedEvent) {
  57373. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57374. }
  57375. if (this._onGamepadDisconnectedEvent) {
  57376. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57377. }
  57378. this._onGamepadConnectedEvent = null;
  57379. this._onGamepadDisconnectedEvent = null;
  57380. }
  57381. this._babylonGamepads.forEach(function (gamepad) {
  57382. gamepad.dispose();
  57383. });
  57384. this.onGamepadConnectedObservable.clear();
  57385. this.onGamepadDisconnectedObservable.clear();
  57386. this._oneGamepadConnected = false;
  57387. this._stopMonitoringGamepads();
  57388. this._babylonGamepads = [];
  57389. };
  57390. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57391. if (!this._oneGamepadConnected) {
  57392. this._oneGamepadConnected = true;
  57393. }
  57394. var newGamepad;
  57395. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57396. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57397. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57398. }
  57399. else if (gamepad.pose) {
  57400. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57401. }
  57402. else {
  57403. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57404. }
  57405. this._babylonGamepads[newGamepad.index] = newGamepad;
  57406. return newGamepad;
  57407. };
  57408. GamepadManager.prototype._startMonitoringGamepads = function () {
  57409. if (!this._isMonitoring) {
  57410. this._isMonitoring = true;
  57411. //back-comp
  57412. if (!this._scene) {
  57413. this._checkGamepadsStatus();
  57414. }
  57415. }
  57416. };
  57417. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57418. this._isMonitoring = false;
  57419. };
  57420. GamepadManager.prototype._checkGamepadsStatus = function () {
  57421. var _this = this;
  57422. // Hack to be compatible Chrome
  57423. this._updateGamepadObjects();
  57424. for (var i in this._babylonGamepads) {
  57425. var gamepad = this._babylonGamepads[i];
  57426. if (!gamepad || !gamepad.isConnected) {
  57427. continue;
  57428. }
  57429. gamepad.update();
  57430. }
  57431. if (this._isMonitoring && !this._scene) {
  57432. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57433. }
  57434. };
  57435. // This function is called only on Chrome, which does not properly support
  57436. // connection/disconnection events and forces you to recopy again the gamepad object
  57437. GamepadManager.prototype._updateGamepadObjects = function () {
  57438. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57439. for (var i = 0; i < gamepads.length; i++) {
  57440. if (gamepads[i]) {
  57441. if (!this._babylonGamepads[gamepads[i].index]) {
  57442. var newGamepad = this._addNewGamepad(gamepads[i]);
  57443. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57444. }
  57445. else {
  57446. // Forced to copy again this object for Chrome for unknown reason
  57447. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57448. if (!this._babylonGamepads[i].isConnected) {
  57449. this._babylonGamepads[i]._isConnected = true;
  57450. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57451. }
  57452. }
  57453. }
  57454. }
  57455. };
  57456. return GamepadManager;
  57457. }());
  57458. BABYLON.GamepadManager = GamepadManager;
  57459. })(BABYLON || (BABYLON = {}));
  57460. //# sourceMappingURL=babylon.gamepadManager.js.map
  57461. var BABYLON;
  57462. (function (BABYLON) {
  57463. var StickValues = /** @class */ (function () {
  57464. function StickValues(x, y) {
  57465. this.x = x;
  57466. this.y = y;
  57467. }
  57468. return StickValues;
  57469. }());
  57470. BABYLON.StickValues = StickValues;
  57471. var Gamepad = /** @class */ (function () {
  57472. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57473. if (leftStickX === void 0) { leftStickX = 0; }
  57474. if (leftStickY === void 0) { leftStickY = 1; }
  57475. if (rightStickX === void 0) { rightStickX = 2; }
  57476. if (rightStickY === void 0) { rightStickY = 3; }
  57477. this.id = id;
  57478. this.index = index;
  57479. this.browserGamepad = browserGamepad;
  57480. this._isConnected = true;
  57481. this._invertLeftStickY = false;
  57482. this.type = Gamepad.GAMEPAD;
  57483. this._leftStickAxisX = leftStickX;
  57484. this._leftStickAxisY = leftStickY;
  57485. this._rightStickAxisX = rightStickX;
  57486. this._rightStickAxisY = rightStickY;
  57487. if (this.browserGamepad.axes.length >= 2) {
  57488. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57489. }
  57490. if (this.browserGamepad.axes.length >= 4) {
  57491. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57492. }
  57493. }
  57494. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57495. get: function () {
  57496. return this._isConnected;
  57497. },
  57498. enumerable: true,
  57499. configurable: true
  57500. });
  57501. Gamepad.prototype.onleftstickchanged = function (callback) {
  57502. this._onleftstickchanged = callback;
  57503. };
  57504. Gamepad.prototype.onrightstickchanged = function (callback) {
  57505. this._onrightstickchanged = callback;
  57506. };
  57507. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57508. get: function () {
  57509. return this._leftStick;
  57510. },
  57511. set: function (newValues) {
  57512. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57513. this._onleftstickchanged(newValues);
  57514. }
  57515. this._leftStick = newValues;
  57516. },
  57517. enumerable: true,
  57518. configurable: true
  57519. });
  57520. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57521. get: function () {
  57522. return this._rightStick;
  57523. },
  57524. set: function (newValues) {
  57525. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57526. this._onrightstickchanged(newValues);
  57527. }
  57528. this._rightStick = newValues;
  57529. },
  57530. enumerable: true,
  57531. configurable: true
  57532. });
  57533. Gamepad.prototype.update = function () {
  57534. if (this._leftStick) {
  57535. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57536. if (this._invertLeftStickY) {
  57537. this.leftStick.y *= -1;
  57538. }
  57539. }
  57540. if (this._rightStick) {
  57541. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57542. }
  57543. };
  57544. Gamepad.prototype.dispose = function () {
  57545. };
  57546. Gamepad.GAMEPAD = 0;
  57547. Gamepad.GENERIC = 1;
  57548. Gamepad.XBOX = 2;
  57549. Gamepad.POSE_ENABLED = 3;
  57550. return Gamepad;
  57551. }());
  57552. BABYLON.Gamepad = Gamepad;
  57553. var GenericPad = /** @class */ (function (_super) {
  57554. __extends(GenericPad, _super);
  57555. function GenericPad(id, index, browserGamepad) {
  57556. var _this = _super.call(this, id, index, browserGamepad) || this;
  57557. _this.onButtonDownObservable = new BABYLON.Observable();
  57558. _this.onButtonUpObservable = new BABYLON.Observable();
  57559. _this.type = Gamepad.GENERIC;
  57560. _this._buttons = new Array(browserGamepad.buttons.length);
  57561. return _this;
  57562. }
  57563. GenericPad.prototype.onbuttondown = function (callback) {
  57564. this._onbuttondown = callback;
  57565. };
  57566. GenericPad.prototype.onbuttonup = function (callback) {
  57567. this._onbuttonup = callback;
  57568. };
  57569. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57570. if (newValue !== currentValue) {
  57571. if (newValue === 1) {
  57572. if (this._onbuttondown) {
  57573. this._onbuttondown(buttonIndex);
  57574. }
  57575. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57576. }
  57577. if (newValue === 0) {
  57578. if (this._onbuttonup) {
  57579. this._onbuttonup(buttonIndex);
  57580. }
  57581. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57582. }
  57583. }
  57584. return newValue;
  57585. };
  57586. GenericPad.prototype.update = function () {
  57587. _super.prototype.update.call(this);
  57588. for (var index = 0; index < this._buttons.length; index++) {
  57589. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57590. }
  57591. };
  57592. GenericPad.prototype.dispose = function () {
  57593. _super.prototype.dispose.call(this);
  57594. this.onButtonDownObservable.clear();
  57595. this.onButtonUpObservable.clear();
  57596. };
  57597. return GenericPad;
  57598. }(Gamepad));
  57599. BABYLON.GenericPad = GenericPad;
  57600. })(BABYLON || (BABYLON = {}));
  57601. //# sourceMappingURL=babylon.gamepad.js.map
  57602. var BABYLON;
  57603. (function (BABYLON) {
  57604. var Xbox360Button;
  57605. (function (Xbox360Button) {
  57606. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57607. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57608. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57609. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57610. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57611. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57612. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57613. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57614. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57615. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57616. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57617. var Xbox360Dpad;
  57618. (function (Xbox360Dpad) {
  57619. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57620. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57621. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57622. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57623. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57624. var Xbox360Pad = /** @class */ (function (_super) {
  57625. __extends(Xbox360Pad, _super);
  57626. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57627. if (xboxOne === void 0) { xboxOne = false; }
  57628. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57629. _this._leftTrigger = 0;
  57630. _this._rightTrigger = 0;
  57631. _this.onButtonDownObservable = new BABYLON.Observable();
  57632. _this.onButtonUpObservable = new BABYLON.Observable();
  57633. _this.onPadDownObservable = new BABYLON.Observable();
  57634. _this.onPadUpObservable = new BABYLON.Observable();
  57635. _this._buttonA = 0;
  57636. _this._buttonB = 0;
  57637. _this._buttonX = 0;
  57638. _this._buttonY = 0;
  57639. _this._buttonBack = 0;
  57640. _this._buttonStart = 0;
  57641. _this._buttonLB = 0;
  57642. _this._buttonRB = 0;
  57643. _this._buttonLeftStick = 0;
  57644. _this._buttonRightStick = 0;
  57645. _this._dPadUp = 0;
  57646. _this._dPadDown = 0;
  57647. _this._dPadLeft = 0;
  57648. _this._dPadRight = 0;
  57649. _this._isXboxOnePad = false;
  57650. _this.type = BABYLON.Gamepad.XBOX;
  57651. _this._isXboxOnePad = xboxOne;
  57652. return _this;
  57653. }
  57654. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57655. this._onlefttriggerchanged = callback;
  57656. };
  57657. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57658. this._onrighttriggerchanged = callback;
  57659. };
  57660. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57661. get: function () {
  57662. return this._leftTrigger;
  57663. },
  57664. set: function (newValue) {
  57665. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57666. this._onlefttriggerchanged(newValue);
  57667. }
  57668. this._leftTrigger = newValue;
  57669. },
  57670. enumerable: true,
  57671. configurable: true
  57672. });
  57673. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57674. get: function () {
  57675. return this._rightTrigger;
  57676. },
  57677. set: function (newValue) {
  57678. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57679. this._onrighttriggerchanged(newValue);
  57680. }
  57681. this._rightTrigger = newValue;
  57682. },
  57683. enumerable: true,
  57684. configurable: true
  57685. });
  57686. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57687. this._onbuttondown = callback;
  57688. };
  57689. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57690. this._onbuttonup = callback;
  57691. };
  57692. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57693. this._ondpaddown = callback;
  57694. };
  57695. Xbox360Pad.prototype.ondpadup = function (callback) {
  57696. this._ondpadup = callback;
  57697. };
  57698. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  57699. if (newValue !== currentValue) {
  57700. if (newValue === 1) {
  57701. if (this._onbuttondown) {
  57702. this._onbuttondown(buttonType);
  57703. }
  57704. this.onButtonDownObservable.notifyObservers(buttonType);
  57705. }
  57706. if (newValue === 0) {
  57707. if (this._onbuttonup) {
  57708. this._onbuttonup(buttonType);
  57709. }
  57710. this.onButtonUpObservable.notifyObservers(buttonType);
  57711. }
  57712. }
  57713. return newValue;
  57714. };
  57715. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  57716. if (newValue !== currentValue) {
  57717. if (newValue === 1) {
  57718. if (this._ondpaddown) {
  57719. this._ondpaddown(buttonType);
  57720. }
  57721. this.onPadDownObservable.notifyObservers(buttonType);
  57722. }
  57723. if (newValue === 0) {
  57724. if (this._ondpadup) {
  57725. this._ondpadup(buttonType);
  57726. }
  57727. this.onPadUpObservable.notifyObservers(buttonType);
  57728. }
  57729. }
  57730. return newValue;
  57731. };
  57732. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  57733. get: function () {
  57734. return this._buttonA;
  57735. },
  57736. set: function (value) {
  57737. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  57738. },
  57739. enumerable: true,
  57740. configurable: true
  57741. });
  57742. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  57743. get: function () {
  57744. return this._buttonB;
  57745. },
  57746. set: function (value) {
  57747. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  57748. },
  57749. enumerable: true,
  57750. configurable: true
  57751. });
  57752. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  57753. get: function () {
  57754. return this._buttonX;
  57755. },
  57756. set: function (value) {
  57757. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  57758. },
  57759. enumerable: true,
  57760. configurable: true
  57761. });
  57762. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  57763. get: function () {
  57764. return this._buttonY;
  57765. },
  57766. set: function (value) {
  57767. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  57768. },
  57769. enumerable: true,
  57770. configurable: true
  57771. });
  57772. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  57773. get: function () {
  57774. return this._buttonStart;
  57775. },
  57776. set: function (value) {
  57777. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  57778. },
  57779. enumerable: true,
  57780. configurable: true
  57781. });
  57782. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  57783. get: function () {
  57784. return this._buttonBack;
  57785. },
  57786. set: function (value) {
  57787. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  57788. },
  57789. enumerable: true,
  57790. configurable: true
  57791. });
  57792. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  57793. get: function () {
  57794. return this._buttonLB;
  57795. },
  57796. set: function (value) {
  57797. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  57798. },
  57799. enumerable: true,
  57800. configurable: true
  57801. });
  57802. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  57803. get: function () {
  57804. return this._buttonRB;
  57805. },
  57806. set: function (value) {
  57807. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  57808. },
  57809. enumerable: true,
  57810. configurable: true
  57811. });
  57812. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  57813. get: function () {
  57814. return this._buttonLeftStick;
  57815. },
  57816. set: function (value) {
  57817. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  57818. },
  57819. enumerable: true,
  57820. configurable: true
  57821. });
  57822. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  57823. get: function () {
  57824. return this._buttonRightStick;
  57825. },
  57826. set: function (value) {
  57827. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  57828. },
  57829. enumerable: true,
  57830. configurable: true
  57831. });
  57832. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  57833. get: function () {
  57834. return this._dPadUp;
  57835. },
  57836. set: function (value) {
  57837. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  57838. },
  57839. enumerable: true,
  57840. configurable: true
  57841. });
  57842. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  57843. get: function () {
  57844. return this._dPadDown;
  57845. },
  57846. set: function (value) {
  57847. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  57848. },
  57849. enumerable: true,
  57850. configurable: true
  57851. });
  57852. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  57853. get: function () {
  57854. return this._dPadLeft;
  57855. },
  57856. set: function (value) {
  57857. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  57858. },
  57859. enumerable: true,
  57860. configurable: true
  57861. });
  57862. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  57863. get: function () {
  57864. return this._dPadRight;
  57865. },
  57866. set: function (value) {
  57867. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  57868. },
  57869. enumerable: true,
  57870. configurable: true
  57871. });
  57872. Xbox360Pad.prototype.update = function () {
  57873. _super.prototype.update.call(this);
  57874. if (this._isXboxOnePad) {
  57875. this.buttonA = this.browserGamepad.buttons[0].value;
  57876. this.buttonB = this.browserGamepad.buttons[1].value;
  57877. this.buttonX = this.browserGamepad.buttons[2].value;
  57878. this.buttonY = this.browserGamepad.buttons[3].value;
  57879. this.buttonLB = this.browserGamepad.buttons[4].value;
  57880. this.buttonRB = this.browserGamepad.buttons[5].value;
  57881. this.leftTrigger = this.browserGamepad.axes[2];
  57882. this.rightTrigger = this.browserGamepad.axes[5];
  57883. this.buttonBack = this.browserGamepad.buttons[9].value;
  57884. this.buttonStart = this.browserGamepad.buttons[8].value;
  57885. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  57886. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  57887. this.dPadUp = this.browserGamepad.buttons[11].value;
  57888. this.dPadDown = this.browserGamepad.buttons[12].value;
  57889. this.dPadLeft = this.browserGamepad.buttons[13].value;
  57890. this.dPadRight = this.browserGamepad.buttons[14].value;
  57891. }
  57892. else {
  57893. this.buttonA = this.browserGamepad.buttons[0].value;
  57894. this.buttonB = this.browserGamepad.buttons[1].value;
  57895. this.buttonX = this.browserGamepad.buttons[2].value;
  57896. this.buttonY = this.browserGamepad.buttons[3].value;
  57897. this.buttonLB = this.browserGamepad.buttons[4].value;
  57898. this.buttonRB = this.browserGamepad.buttons[5].value;
  57899. this.leftTrigger = this.browserGamepad.buttons[6].value;
  57900. this.rightTrigger = this.browserGamepad.buttons[7].value;
  57901. this.buttonBack = this.browserGamepad.buttons[8].value;
  57902. this.buttonStart = this.browserGamepad.buttons[9].value;
  57903. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  57904. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  57905. this.dPadUp = this.browserGamepad.buttons[12].value;
  57906. this.dPadDown = this.browserGamepad.buttons[13].value;
  57907. this.dPadLeft = this.browserGamepad.buttons[14].value;
  57908. this.dPadRight = this.browserGamepad.buttons[15].value;
  57909. }
  57910. };
  57911. Xbox360Pad.prototype.dispose = function () {
  57912. _super.prototype.dispose.call(this);
  57913. this.onButtonDownObservable.clear();
  57914. this.onButtonUpObservable.clear();
  57915. this.onPadDownObservable.clear();
  57916. this.onPadUpObservable.clear();
  57917. };
  57918. return Xbox360Pad;
  57919. }(BABYLON.Gamepad));
  57920. BABYLON.Xbox360Pad = Xbox360Pad;
  57921. })(BABYLON || (BABYLON = {}));
  57922. //# sourceMappingURL=babylon.xboxGamepad.js.map
  57923. var BABYLON;
  57924. (function (BABYLON) {
  57925. var PoseEnabledControllerType;
  57926. (function (PoseEnabledControllerType) {
  57927. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  57928. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  57929. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  57930. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  57931. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  57932. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  57933. var PoseEnabledControllerHelper = /** @class */ (function () {
  57934. function PoseEnabledControllerHelper() {
  57935. }
  57936. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  57937. // Oculus Touch
  57938. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  57939. return new BABYLON.OculusTouchController(vrGamepad);
  57940. }
  57941. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  57942. return new BABYLON.WindowsMotionController(vrGamepad);
  57943. }
  57944. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  57945. return new BABYLON.ViveController(vrGamepad);
  57946. }
  57947. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  57948. return new BABYLON.GearVRController(vrGamepad);
  57949. }
  57950. else {
  57951. return new BABYLON.GenericController(vrGamepad);
  57952. }
  57953. };
  57954. return PoseEnabledControllerHelper;
  57955. }());
  57956. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  57957. var PoseEnabledController = /** @class */ (function (_super) {
  57958. __extends(PoseEnabledController, _super);
  57959. function PoseEnabledController(browserGamepad) {
  57960. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  57961. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  57962. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  57963. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  57964. // Represents device position and rotation in babylon space
  57965. _this.devicePosition = BABYLON.Vector3.Zero();
  57966. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57967. _this.deviceScaleFactor = 1;
  57968. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  57969. _this._deviceToWorld = BABYLON.Matrix.Identity();
  57970. _this._workingMatrix = BABYLON.Matrix.Identity();
  57971. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  57972. _this.controllerType = PoseEnabledControllerType.GENERIC;
  57973. _this.position = BABYLON.Vector3.Zero();
  57974. _this.rotationQuaternion = new BABYLON.Quaternion();
  57975. _this._calculatedPosition = BABYLON.Vector3.Zero();
  57976. _this._calculatedRotation = new BABYLON.Quaternion();
  57977. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  57978. return _this;
  57979. }
  57980. PoseEnabledController.prototype.update = function () {
  57981. _super.prototype.update.call(this);
  57982. var pose = this.browserGamepad.pose;
  57983. this.updateFromDevice(pose);
  57984. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  57985. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  57986. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  57987. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  57988. if (this._mesh) {
  57989. this._mesh.position.copyFrom(this.devicePosition);
  57990. if (this._mesh.rotationQuaternion) {
  57991. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57992. }
  57993. }
  57994. };
  57995. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  57996. if (poseData) {
  57997. this.rawPose = poseData;
  57998. if (poseData.position) {
  57999. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58000. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58001. this._deviceRoomPosition.z *= -1;
  58002. }
  58003. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58004. this._calculatedPosition.addInPlace(this.position);
  58005. }
  58006. var pose = this.rawPose;
  58007. if (poseData.orientation && pose.orientation) {
  58008. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58009. if (this._mesh) {
  58010. if (this._mesh.getScene().useRightHandedSystem) {
  58011. this._deviceRoomRotationQuaternion.z *= -1;
  58012. this._deviceRoomRotationQuaternion.w *= -1;
  58013. }
  58014. else {
  58015. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58016. }
  58017. }
  58018. // if the camera is set, rotate to the camera's rotation
  58019. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58020. }
  58021. }
  58022. };
  58023. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58024. if (this._mesh) {
  58025. this._mesh.parent = null;
  58026. }
  58027. this._mesh = mesh;
  58028. if (this._poseControlledCamera) {
  58029. this._mesh.parent = this._poseControlledCamera;
  58030. }
  58031. if (!this._mesh.rotationQuaternion) {
  58032. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58033. }
  58034. };
  58035. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58036. this._poseControlledCamera = camera;
  58037. if (this._mesh) {
  58038. this._mesh.parent = this._poseControlledCamera;
  58039. }
  58040. };
  58041. PoseEnabledController.prototype.dispose = function () {
  58042. if (this._mesh) {
  58043. this._mesh.dispose();
  58044. }
  58045. this._mesh = null;
  58046. _super.prototype.dispose.call(this);
  58047. };
  58048. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58049. get: function () {
  58050. return this._mesh;
  58051. },
  58052. enumerable: true,
  58053. configurable: true
  58054. });
  58055. PoseEnabledController.prototype.getForwardRay = function (length) {
  58056. if (length === void 0) { length = 100; }
  58057. if (!this.mesh) {
  58058. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58059. }
  58060. var m = this.mesh.getWorldMatrix();
  58061. var origin = m.getTranslation();
  58062. var forward = new BABYLON.Vector3(0, 0, -1);
  58063. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58064. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58065. return new BABYLON.Ray(origin, direction, length);
  58066. };
  58067. return PoseEnabledController;
  58068. }(BABYLON.Gamepad));
  58069. BABYLON.PoseEnabledController = PoseEnabledController;
  58070. })(BABYLON || (BABYLON = {}));
  58071. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58072. var BABYLON;
  58073. (function (BABYLON) {
  58074. var WebVRController = /** @class */ (function (_super) {
  58075. __extends(WebVRController, _super);
  58076. function WebVRController(vrGamepad) {
  58077. var _this = _super.call(this, vrGamepad) || this;
  58078. // Observables
  58079. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58080. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58081. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58082. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58083. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58084. _this.pad = { x: 0, y: 0 };
  58085. // avoid GC, store state in a tmp object
  58086. _this._changes = {
  58087. pressChanged: false,
  58088. touchChanged: false,
  58089. valueChanged: false,
  58090. changed: false
  58091. };
  58092. _this._buttons = new Array(vrGamepad.buttons.length);
  58093. _this.hand = vrGamepad.hand;
  58094. return _this;
  58095. }
  58096. WebVRController.prototype.onButtonStateChange = function (callback) {
  58097. this._onButtonStateChange = callback;
  58098. };
  58099. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58100. get: function () {
  58101. return this._defaultModel;
  58102. },
  58103. enumerable: true,
  58104. configurable: true
  58105. });
  58106. WebVRController.prototype.update = function () {
  58107. _super.prototype.update.call(this);
  58108. for (var index = 0; index < this._buttons.length; index++) {
  58109. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58110. }
  58111. ;
  58112. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58113. this.pad.x = this.leftStick.x;
  58114. this.pad.y = this.leftStick.y;
  58115. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58116. }
  58117. };
  58118. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58119. if (!newState) {
  58120. newState = {
  58121. pressed: false,
  58122. touched: false,
  58123. value: 0
  58124. };
  58125. }
  58126. if (!currentState) {
  58127. this._buttons[buttonIndex] = {
  58128. pressed: newState.pressed,
  58129. touched: newState.touched,
  58130. value: newState.value
  58131. };
  58132. return;
  58133. }
  58134. this._checkChanges(newState, currentState);
  58135. if (this._changes.changed) {
  58136. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58137. this.handleButtonChange(buttonIndex, newState, this._changes);
  58138. }
  58139. this._buttons[buttonIndex].pressed = newState.pressed;
  58140. this._buttons[buttonIndex].touched = newState.touched;
  58141. // oculus triggers are never 0, thou not touched.
  58142. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58143. };
  58144. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58145. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58146. this._changes.touchChanged = newState.touched !== currentState.touched;
  58147. this._changes.valueChanged = newState.value !== currentState.value;
  58148. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58149. return this._changes;
  58150. };
  58151. WebVRController.prototype.dispose = function () {
  58152. _super.prototype.dispose.call(this);
  58153. this.onTriggerStateChangedObservable.clear();
  58154. this.onMainButtonStateChangedObservable.clear();
  58155. this.onSecondaryButtonStateChangedObservable.clear();
  58156. this.onPadStateChangedObservable.clear();
  58157. this.onPadValuesChangedObservable.clear();
  58158. };
  58159. return WebVRController;
  58160. }(BABYLON.PoseEnabledController));
  58161. BABYLON.WebVRController = WebVRController;
  58162. })(BABYLON || (BABYLON = {}));
  58163. //# sourceMappingURL=babylon.webVRController.js.map
  58164. var BABYLON;
  58165. (function (BABYLON) {
  58166. var OculusTouchController = /** @class */ (function (_super) {
  58167. __extends(OculusTouchController, _super);
  58168. function OculusTouchController(vrGamepad) {
  58169. var _this = _super.call(this, vrGamepad) || this;
  58170. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58171. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58172. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58173. return _this;
  58174. }
  58175. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58176. var _this = this;
  58177. var meshName;
  58178. // Hand
  58179. if (this.hand === 'left') {
  58180. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58181. }
  58182. else {
  58183. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58184. }
  58185. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58186. /*
  58187. Parent Mesh name: oculus_touch_left
  58188. - body
  58189. - trigger
  58190. - thumbstick
  58191. - grip
  58192. - button_y
  58193. - button_x
  58194. - button_enter
  58195. */
  58196. _this._defaultModel = newMeshes[1];
  58197. _this.attachToMesh(_this._defaultModel);
  58198. if (meshLoaded) {
  58199. meshLoaded(_this._defaultModel);
  58200. }
  58201. });
  58202. };
  58203. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58204. // helper getters for left and right hand.
  58205. get: function () {
  58206. if (this.hand === 'right') {
  58207. return this.onMainButtonStateChangedObservable;
  58208. }
  58209. else {
  58210. throw new Error('No A button on left hand');
  58211. }
  58212. },
  58213. enumerable: true,
  58214. configurable: true
  58215. });
  58216. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58217. get: function () {
  58218. if (this.hand === 'right') {
  58219. return this.onSecondaryButtonStateChangedObservable;
  58220. }
  58221. else {
  58222. throw new Error('No B button on left hand');
  58223. }
  58224. },
  58225. enumerable: true,
  58226. configurable: true
  58227. });
  58228. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58229. get: function () {
  58230. if (this.hand === 'left') {
  58231. return this.onMainButtonStateChangedObservable;
  58232. }
  58233. else {
  58234. throw new Error('No X button on right hand');
  58235. }
  58236. },
  58237. enumerable: true,
  58238. configurable: true
  58239. });
  58240. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58241. get: function () {
  58242. if (this.hand === 'left') {
  58243. return this.onSecondaryButtonStateChangedObservable;
  58244. }
  58245. else {
  58246. throw new Error('No Y button on right hand');
  58247. }
  58248. },
  58249. enumerable: true,
  58250. configurable: true
  58251. });
  58252. /*
  58253. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58254. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58255. 2) secondary trigger (same)
  58256. 3) A (right) X (left), touch, pressed = value
  58257. 4) B / Y
  58258. 5) thumb rest
  58259. */
  58260. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58261. var notifyObject = state; //{ state: state, changes: changes };
  58262. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58263. switch (buttonIdx) {
  58264. case 0:
  58265. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58266. return;
  58267. case 1:// index trigger
  58268. if (this._defaultModel) {
  58269. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58270. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58271. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58272. }
  58273. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58274. return;
  58275. case 2:// secondary trigger
  58276. if (this._defaultModel) {
  58277. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58278. }
  58279. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58280. return;
  58281. case 3:
  58282. if (this._defaultModel) {
  58283. if (notifyObject.pressed) {
  58284. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58285. }
  58286. else {
  58287. (this._defaultModel.getChildren()[1]).position.y = 0;
  58288. }
  58289. }
  58290. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58291. return;
  58292. case 4:
  58293. if (this._defaultModel) {
  58294. if (notifyObject.pressed) {
  58295. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58296. }
  58297. else {
  58298. (this._defaultModel.getChildren()[2]).position.y = 0;
  58299. }
  58300. }
  58301. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58302. return;
  58303. case 5:
  58304. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58305. return;
  58306. }
  58307. };
  58308. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58309. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58310. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58311. return OculusTouchController;
  58312. }(BABYLON.WebVRController));
  58313. BABYLON.OculusTouchController = OculusTouchController;
  58314. })(BABYLON || (BABYLON = {}));
  58315. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58316. var BABYLON;
  58317. (function (BABYLON) {
  58318. var ViveController = /** @class */ (function (_super) {
  58319. __extends(ViveController, _super);
  58320. function ViveController(vrGamepad) {
  58321. var _this = _super.call(this, vrGamepad) || this;
  58322. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58323. _this._invertLeftStickY = true;
  58324. return _this;
  58325. }
  58326. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58327. var _this = this;
  58328. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58329. /*
  58330. Parent Mesh name: ViveWand
  58331. - body
  58332. - r_gripper
  58333. - l_gripper
  58334. - menu_button
  58335. - system_button
  58336. - trackpad
  58337. - trigger
  58338. - LED
  58339. */
  58340. _this._defaultModel = newMeshes[1];
  58341. _this.attachToMesh(_this._defaultModel);
  58342. if (meshLoaded) {
  58343. meshLoaded(_this._defaultModel);
  58344. }
  58345. });
  58346. };
  58347. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58348. get: function () {
  58349. return this.onMainButtonStateChangedObservable;
  58350. },
  58351. enumerable: true,
  58352. configurable: true
  58353. });
  58354. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58355. get: function () {
  58356. return this.onMainButtonStateChangedObservable;
  58357. },
  58358. enumerable: true,
  58359. configurable: true
  58360. });
  58361. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58362. get: function () {
  58363. return this.onSecondaryButtonStateChangedObservable;
  58364. },
  58365. enumerable: true,
  58366. configurable: true
  58367. });
  58368. /**
  58369. * Vive mapping:
  58370. * 0: touchpad
  58371. * 1: trigger
  58372. * 2: left AND right buttons
  58373. * 3: menu button
  58374. */
  58375. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58376. var notifyObject = state; //{ state: state, changes: changes };
  58377. switch (buttonIdx) {
  58378. case 0:
  58379. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58380. return;
  58381. case 1:// index trigger
  58382. if (this._defaultModel) {
  58383. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58384. }
  58385. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58386. return;
  58387. case 2:// left AND right button
  58388. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58389. return;
  58390. case 3:
  58391. if (this._defaultModel) {
  58392. if (notifyObject.pressed) {
  58393. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58394. }
  58395. else {
  58396. (this._defaultModel.getChildren()[2]).position.y = 0;
  58397. }
  58398. }
  58399. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58400. return;
  58401. }
  58402. };
  58403. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58404. ViveController.MODEL_FILENAME = 'wand.babylon';
  58405. return ViveController;
  58406. }(BABYLON.WebVRController));
  58407. BABYLON.ViveController = ViveController;
  58408. })(BABYLON || (BABYLON = {}));
  58409. //# sourceMappingURL=babylon.viveController.js.map
  58410. var BABYLON;
  58411. (function (BABYLON) {
  58412. var GenericController = /** @class */ (function (_super) {
  58413. __extends(GenericController, _super);
  58414. function GenericController(vrGamepad) {
  58415. return _super.call(this, vrGamepad) || this;
  58416. }
  58417. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58418. var _this = this;
  58419. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58420. _this._defaultModel = newMeshes[1];
  58421. _this.attachToMesh(_this._defaultModel);
  58422. if (meshLoaded) {
  58423. meshLoaded(_this._defaultModel);
  58424. }
  58425. });
  58426. };
  58427. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58428. console.log("Button id: " + buttonIdx + "state: ");
  58429. console.dir(state);
  58430. };
  58431. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58432. GenericController.MODEL_FILENAME = 'generic.babylon';
  58433. return GenericController;
  58434. }(BABYLON.WebVRController));
  58435. BABYLON.GenericController = GenericController;
  58436. })(BABYLON || (BABYLON = {}));
  58437. //# sourceMappingURL=babylon.genericController.js.map
  58438. var BABYLON;
  58439. (function (BABYLON) {
  58440. var LoadedMeshInfo = /** @class */ (function () {
  58441. function LoadedMeshInfo() {
  58442. this.buttonMeshes = {};
  58443. this.axisMeshes = {};
  58444. }
  58445. return LoadedMeshInfo;
  58446. }());
  58447. var WindowsMotionController = /** @class */ (function (_super) {
  58448. __extends(WindowsMotionController, _super);
  58449. function WindowsMotionController(vrGamepad) {
  58450. var _this = _super.call(this, vrGamepad) || this;
  58451. _this._mapping = {
  58452. // Semantic button names
  58453. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58454. // A mapping of the button name to glTF model node name
  58455. // that should be transformed by button value.
  58456. buttonMeshNames: {
  58457. 'trigger': 'SELECT',
  58458. 'menu': 'MENU',
  58459. 'grip': 'GRASP',
  58460. 'thumbstick': 'THUMBSTICK_PRESS',
  58461. 'trackpad': 'TOUCHPAD_PRESS'
  58462. },
  58463. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58464. buttonObservableNames: {
  58465. 'trigger': 'onTriggerStateChangedObservable',
  58466. 'menu': 'onSecondaryButtonStateChangedObservable',
  58467. 'grip': 'onMainButtonStateChangedObservable',
  58468. 'thumbstick': 'onPadStateChangedObservable',
  58469. 'trackpad': 'onTrackpadChangedObservable'
  58470. },
  58471. // A mapping of the axis name to glTF model node name
  58472. // that should be transformed by axis value.
  58473. // This array mirrors the browserGamepad.axes array, such that
  58474. // the mesh corresponding to axis 0 is in this array index 0.
  58475. axisMeshNames: [
  58476. 'THUMBSTICK_X',
  58477. 'THUMBSTICK_Y',
  58478. 'TOUCHPAD_TOUCH_X',
  58479. 'TOUCHPAD_TOUCH_Y'
  58480. ],
  58481. pointingPoseMeshName: 'POINTING_POSE'
  58482. };
  58483. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58484. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58485. _this.trackpad = { x: 0, y: 0 };
  58486. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58487. _this._loadedMeshInfo = null;
  58488. return _this;
  58489. }
  58490. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58491. get: function () {
  58492. return this.onTriggerStateChangedObservable;
  58493. },
  58494. enumerable: true,
  58495. configurable: true
  58496. });
  58497. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58498. get: function () {
  58499. return this.onSecondaryButtonStateChangedObservable;
  58500. },
  58501. enumerable: true,
  58502. configurable: true
  58503. });
  58504. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58505. get: function () {
  58506. return this.onMainButtonStateChangedObservable;
  58507. },
  58508. enumerable: true,
  58509. configurable: true
  58510. });
  58511. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58512. get: function () {
  58513. return this.onPadStateChangedObservable;
  58514. },
  58515. enumerable: true,
  58516. configurable: true
  58517. });
  58518. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58519. get: function () {
  58520. return this.onTrackpadChangedObservable;
  58521. },
  58522. enumerable: true,
  58523. configurable: true
  58524. });
  58525. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58526. get: function () {
  58527. return this.onTrackpadValuesChangedObservable;
  58528. },
  58529. enumerable: true,
  58530. configurable: true
  58531. });
  58532. /**
  58533. * Called once per frame by the engine.
  58534. */
  58535. WindowsMotionController.prototype.update = function () {
  58536. _super.prototype.update.call(this);
  58537. // Only need to animate axes if there is a loaded mesh
  58538. if (this._loadedMeshInfo) {
  58539. if (this.browserGamepad.axes) {
  58540. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58541. this.trackpad.x = this.browserGamepad["axes"][2];
  58542. this.trackpad.y = this.browserGamepad["axes"][3];
  58543. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58544. }
  58545. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58546. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58547. }
  58548. }
  58549. }
  58550. };
  58551. /**
  58552. * Called once for each button that changed state since the last frame
  58553. * @param buttonIdx Which button index changed
  58554. * @param state New state of the button
  58555. * @param changes Which properties on the state changed since last frame
  58556. */
  58557. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58558. var buttonName = this._mapping.buttons[buttonIdx];
  58559. if (!buttonName) {
  58560. return;
  58561. }
  58562. // Only emit events for buttons that we know how to map from index to name
  58563. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58564. if (observable) {
  58565. observable.notifyObservers(state);
  58566. }
  58567. this.lerpButtonTransform(buttonName, state.value);
  58568. };
  58569. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58570. // If there is no loaded mesh, there is nothing to transform.
  58571. if (!this._loadedMeshInfo) {
  58572. return;
  58573. }
  58574. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58575. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58576. return;
  58577. }
  58578. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58579. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58580. };
  58581. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58582. if (!this._loadedMeshInfo) {
  58583. return;
  58584. }
  58585. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58586. if (!meshInfo) {
  58587. return;
  58588. }
  58589. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58590. return;
  58591. }
  58592. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58593. var lerpValue = axisValue * 0.5 + 0.5;
  58594. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58595. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58596. };
  58597. /**
  58598. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58599. * @param scene scene in which to add meshes
  58600. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58601. */
  58602. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58603. var _this = this;
  58604. if (forceDefault === void 0) { forceDefault = false; }
  58605. var path;
  58606. var filename;
  58607. // Checking if GLB loader is present
  58608. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58609. // Determine the device specific folder based on the ID suffix
  58610. var device = 'default';
  58611. if (this.id && !forceDefault) {
  58612. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58613. device = ((match && match[0]) || device);
  58614. }
  58615. // Hand
  58616. if (this.hand === 'left') {
  58617. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58618. }
  58619. else {
  58620. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58621. }
  58622. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58623. }
  58624. else {
  58625. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58626. path = BABYLON.GenericController.MODEL_BASE_URL;
  58627. filename = BABYLON.GenericController.MODEL_FILENAME;
  58628. }
  58629. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58630. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58631. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58632. if (!_this._loadedMeshInfo) {
  58633. return;
  58634. }
  58635. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58636. _this.attachToMesh(_this._defaultModel);
  58637. if (meshLoaded) {
  58638. meshLoaded(_this._defaultModel);
  58639. }
  58640. }, null, function (scene, message) {
  58641. BABYLON.Tools.Log(message);
  58642. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58643. if (!forceDefault) {
  58644. _this.initControllerMesh(scene, meshLoaded, true);
  58645. }
  58646. });
  58647. };
  58648. /**
  58649. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58650. * can be transformed by button presses and axes values, based on this._mapping.
  58651. *
  58652. * @param scene scene in which the meshes exist
  58653. * @param meshes list of meshes that make up the controller model to process
  58654. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58655. */
  58656. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58657. var loadedMeshInfo = null;
  58658. // Create a new mesh to contain the glTF hierarchy
  58659. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58660. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58661. var childMesh = null;
  58662. for (var i = 0; i < meshes.length; i++) {
  58663. var mesh = meshes[i];
  58664. if (!mesh.parent) {
  58665. // Exclude controller meshes from picking results
  58666. mesh.isPickable = false;
  58667. // Handle root node, attach to the new parentMesh
  58668. childMesh = mesh;
  58669. break;
  58670. }
  58671. }
  58672. if (childMesh) {
  58673. childMesh.setParent(parentMesh);
  58674. // Create our mesh info. Note that this method will always return non-null.
  58675. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58676. }
  58677. else {
  58678. BABYLON.Tools.Warn('Could not find root node in model file.');
  58679. }
  58680. return loadedMeshInfo;
  58681. };
  58682. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58683. var loadedMeshInfo = new LoadedMeshInfo();
  58684. var i;
  58685. loadedMeshInfo.rootNode = rootNode;
  58686. // Reset the caches
  58687. loadedMeshInfo.buttonMeshes = {};
  58688. loadedMeshInfo.axisMeshes = {};
  58689. // Button Meshes
  58690. for (i = 0; i < this._mapping.buttons.length; i++) {
  58691. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58692. if (!buttonMeshName) {
  58693. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58694. continue;
  58695. }
  58696. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  58697. if (!buttonMesh) {
  58698. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  58699. continue;
  58700. }
  58701. var buttonMeshInfo = {
  58702. index: i,
  58703. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  58704. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  58705. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  58706. };
  58707. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  58708. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  58709. }
  58710. else {
  58711. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  58712. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  58713. '(VALUE: ' + !!buttonMeshInfo.value +
  58714. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  58715. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  58716. ')');
  58717. }
  58718. }
  58719. // Axis Meshes
  58720. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  58721. var axisMeshName = this._mapping.axisMeshNames[i];
  58722. if (!axisMeshName) {
  58723. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  58724. continue;
  58725. }
  58726. var axisMesh = getChildByName(rootNode, axisMeshName);
  58727. if (!axisMesh) {
  58728. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  58729. continue;
  58730. }
  58731. var axisMeshInfo = {
  58732. index: i,
  58733. value: getImmediateChildByName(axisMesh, 'VALUE'),
  58734. min: getImmediateChildByName(axisMesh, 'MIN'),
  58735. max: getImmediateChildByName(axisMesh, 'MAX')
  58736. };
  58737. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  58738. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  58739. }
  58740. else {
  58741. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  58742. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  58743. '(VALUE: ' + !!axisMeshInfo.value +
  58744. ', MIN: ' + !!axisMeshInfo.min +
  58745. ', MAX:' + !!axisMeshInfo.max +
  58746. ')');
  58747. }
  58748. }
  58749. // Pointing Ray
  58750. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  58751. if (!loadedMeshInfo.pointingPoseNode) {
  58752. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  58753. }
  58754. return loadedMeshInfo;
  58755. // Look through all children recursively. This will return null if no mesh exists with the given name.
  58756. function getChildByName(node, name) {
  58757. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  58758. }
  58759. // Look through only immediate children. This will return null if no mesh exists with the given name.
  58760. function getImmediateChildByName(node, name) {
  58761. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  58762. }
  58763. };
  58764. WindowsMotionController.prototype.getForwardRay = function (length) {
  58765. if (length === void 0) { length = 100; }
  58766. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  58767. return _super.prototype.getForwardRay.call(this, length);
  58768. }
  58769. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  58770. var origin = m.getTranslation();
  58771. var forward = new BABYLON.Vector3(0, 0, -1);
  58772. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58773. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58774. return new BABYLON.Ray(origin, direction, length);
  58775. };
  58776. WindowsMotionController.prototype.dispose = function () {
  58777. _super.prototype.dispose.call(this);
  58778. this.onTrackpadChangedObservable.clear();
  58779. };
  58780. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  58781. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  58782. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  58783. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  58784. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  58785. return WindowsMotionController;
  58786. }(BABYLON.WebVRController));
  58787. BABYLON.WindowsMotionController = WindowsMotionController;
  58788. })(BABYLON || (BABYLON = {}));
  58789. //# sourceMappingURL=babylon.windowsMotionController.js.map
  58790. var BABYLON;
  58791. (function (BABYLON) {
  58792. var GearVRController = /** @class */ (function (_super) {
  58793. __extends(GearVRController, _super);
  58794. function GearVRController(vrGamepad) {
  58795. var _this = _super.call(this, vrGamepad) || this;
  58796. _this._buttonIndexToObservableNameMap = [
  58797. 'onTrackpadChangedObservable',
  58798. 'onTriggerStateChangedObservable' // Trigger
  58799. ];
  58800. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  58801. return _this;
  58802. }
  58803. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58804. var _this = this;
  58805. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  58806. _this._defaultModel = newMeshes[1];
  58807. _this.attachToMesh(_this._defaultModel);
  58808. if (meshLoaded) {
  58809. meshLoaded(_this._defaultModel);
  58810. }
  58811. });
  58812. };
  58813. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58814. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  58815. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  58816. // Only emit events for buttons that we know how to map from index to observable
  58817. var observable = this[observableName];
  58818. if (observable) {
  58819. observable.notifyObservers(state);
  58820. }
  58821. }
  58822. };
  58823. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58824. GearVRController.MODEL_FILENAME = 'generic.babylon';
  58825. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  58826. return GearVRController;
  58827. }(BABYLON.WebVRController));
  58828. BABYLON.GearVRController = GearVRController;
  58829. })(BABYLON || (BABYLON = {}));
  58830. //# sourceMappingURL=babylon.gearVRController.js.map
  58831. var BABYLON;
  58832. (function (BABYLON) {
  58833. var FollowCamera = /** @class */ (function (_super) {
  58834. __extends(FollowCamera, _super);
  58835. function FollowCamera(name, position, scene, lockedTarget) {
  58836. if (lockedTarget === void 0) { lockedTarget = null; }
  58837. var _this = _super.call(this, name, position, scene) || this;
  58838. _this.radius = 12;
  58839. _this.rotationOffset = 0;
  58840. _this.heightOffset = 4;
  58841. _this.cameraAcceleration = 0.05;
  58842. _this.maxCameraSpeed = 20;
  58843. _this.lockedTarget = lockedTarget;
  58844. return _this;
  58845. }
  58846. FollowCamera.prototype.getRadians = function (degrees) {
  58847. return degrees * Math.PI / 180;
  58848. };
  58849. FollowCamera.prototype.follow = function (cameraTarget) {
  58850. if (!cameraTarget)
  58851. return;
  58852. var yRotation;
  58853. if (cameraTarget.rotationQuaternion) {
  58854. var rotMatrix = new BABYLON.Matrix();
  58855. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  58856. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  58857. }
  58858. else {
  58859. yRotation = cameraTarget.rotation.y;
  58860. }
  58861. var radians = this.getRadians(this.rotationOffset) + yRotation;
  58862. var targetPosition = cameraTarget.getAbsolutePosition();
  58863. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  58864. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  58865. var dx = targetX - this.position.x;
  58866. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  58867. var dz = (targetZ) - this.position.z;
  58868. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  58869. var vy = dy * this.cameraAcceleration;
  58870. var vz = dz * this.cameraAcceleration * 2;
  58871. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  58872. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58873. }
  58874. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  58875. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58876. }
  58877. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  58878. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58879. }
  58880. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  58881. this.setTarget(targetPosition);
  58882. };
  58883. FollowCamera.prototype._checkInputs = function () {
  58884. _super.prototype._checkInputs.call(this);
  58885. if (this.lockedTarget) {
  58886. this.follow(this.lockedTarget);
  58887. }
  58888. };
  58889. FollowCamera.prototype.getClassName = function () {
  58890. return "FollowCamera";
  58891. };
  58892. __decorate([
  58893. BABYLON.serialize()
  58894. ], FollowCamera.prototype, "radius", void 0);
  58895. __decorate([
  58896. BABYLON.serialize()
  58897. ], FollowCamera.prototype, "rotationOffset", void 0);
  58898. __decorate([
  58899. BABYLON.serialize()
  58900. ], FollowCamera.prototype, "heightOffset", void 0);
  58901. __decorate([
  58902. BABYLON.serialize()
  58903. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  58904. __decorate([
  58905. BABYLON.serialize()
  58906. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  58907. __decorate([
  58908. BABYLON.serializeAsMeshReference("lockedTargetId")
  58909. ], FollowCamera.prototype, "lockedTarget", void 0);
  58910. return FollowCamera;
  58911. }(BABYLON.TargetCamera));
  58912. BABYLON.FollowCamera = FollowCamera;
  58913. var ArcFollowCamera = /** @class */ (function (_super) {
  58914. __extends(ArcFollowCamera, _super);
  58915. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  58916. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  58917. _this.alpha = alpha;
  58918. _this.beta = beta;
  58919. _this.radius = radius;
  58920. _this.target = target;
  58921. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  58922. _this.follow();
  58923. return _this;
  58924. }
  58925. ArcFollowCamera.prototype.follow = function () {
  58926. if (!this.target) {
  58927. return;
  58928. }
  58929. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  58930. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  58931. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  58932. var targetPosition = this.target.getAbsolutePosition();
  58933. this.position = targetPosition.add(this._cartesianCoordinates);
  58934. this.setTarget(targetPosition);
  58935. };
  58936. ArcFollowCamera.prototype._checkInputs = function () {
  58937. _super.prototype._checkInputs.call(this);
  58938. this.follow();
  58939. };
  58940. ArcFollowCamera.prototype.getClassName = function () {
  58941. return "ArcFollowCamera";
  58942. };
  58943. return ArcFollowCamera;
  58944. }(BABYLON.TargetCamera));
  58945. BABYLON.ArcFollowCamera = ArcFollowCamera;
  58946. })(BABYLON || (BABYLON = {}));
  58947. //# sourceMappingURL=babylon.followCamera.js.map
  58948. var BABYLON;
  58949. (function (BABYLON) {
  58950. // We're mainly based on the logic defined into the FreeCamera code
  58951. var UniversalCamera = /** @class */ (function (_super) {
  58952. __extends(UniversalCamera, _super);
  58953. //-- end properties for backward compatibility for inputs
  58954. function UniversalCamera(name, position, scene) {
  58955. var _this = _super.call(this, name, position, scene) || this;
  58956. _this.inputs.addGamepad();
  58957. return _this;
  58958. }
  58959. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  58960. //-- Begin properties for backward compatibility for inputs
  58961. get: function () {
  58962. var gamepad = this.inputs.attached["gamepad"];
  58963. if (gamepad)
  58964. return gamepad.gamepadAngularSensibility;
  58965. return 0;
  58966. },
  58967. set: function (value) {
  58968. var gamepad = this.inputs.attached["gamepad"];
  58969. if (gamepad)
  58970. gamepad.gamepadAngularSensibility = value;
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  58976. get: function () {
  58977. var gamepad = this.inputs.attached["gamepad"];
  58978. if (gamepad)
  58979. return gamepad.gamepadMoveSensibility;
  58980. return 0;
  58981. },
  58982. set: function (value) {
  58983. var gamepad = this.inputs.attached["gamepad"];
  58984. if (gamepad)
  58985. gamepad.gamepadMoveSensibility = value;
  58986. },
  58987. enumerable: true,
  58988. configurable: true
  58989. });
  58990. UniversalCamera.prototype.getClassName = function () {
  58991. return "UniversalCamera";
  58992. };
  58993. return UniversalCamera;
  58994. }(BABYLON.TouchCamera));
  58995. BABYLON.UniversalCamera = UniversalCamera;
  58996. })(BABYLON || (BABYLON = {}));
  58997. //# sourceMappingURL=babylon.universalCamera.js.map
  58998. var BABYLON;
  58999. (function (BABYLON) {
  59000. // We're mainly based on the logic defined into the FreeCamera code
  59001. var GamepadCamera = /** @class */ (function (_super) {
  59002. __extends(GamepadCamera, _super);
  59003. //-- end properties for backward compatibility for inputs
  59004. function GamepadCamera(name, position, scene) {
  59005. return _super.call(this, name, position, scene) || this;
  59006. }
  59007. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59008. //-- Begin properties for backward compatibility for inputs
  59009. get: function () {
  59010. var gamepad = this.inputs.attached["gamepad"];
  59011. if (gamepad)
  59012. return gamepad.gamepadAngularSensibility;
  59013. return 0;
  59014. },
  59015. set: function (value) {
  59016. var gamepad = this.inputs.attached["gamepad"];
  59017. if (gamepad)
  59018. gamepad.gamepadAngularSensibility = value;
  59019. },
  59020. enumerable: true,
  59021. configurable: true
  59022. });
  59023. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59024. get: function () {
  59025. var gamepad = this.inputs.attached["gamepad"];
  59026. if (gamepad)
  59027. return gamepad.gamepadMoveSensibility;
  59028. return 0;
  59029. },
  59030. set: function (value) {
  59031. var gamepad = this.inputs.attached["gamepad"];
  59032. if (gamepad)
  59033. gamepad.gamepadMoveSensibility = value;
  59034. },
  59035. enumerable: true,
  59036. configurable: true
  59037. });
  59038. GamepadCamera.prototype.getClassName = function () {
  59039. return "GamepadCamera";
  59040. };
  59041. return GamepadCamera;
  59042. }(BABYLON.UniversalCamera));
  59043. BABYLON.GamepadCamera = GamepadCamera;
  59044. })(BABYLON || (BABYLON = {}));
  59045. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59046. var BABYLON;
  59047. (function (BABYLON) {
  59048. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59049. function PostProcessRenderPipelineManager() {
  59050. this._renderPipelines = {};
  59051. }
  59052. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59053. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59054. };
  59055. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59056. if (unique === void 0) { unique = false; }
  59057. var renderPipeline = this._renderPipelines[renderPipelineName];
  59058. if (!renderPipeline) {
  59059. return;
  59060. }
  59061. renderPipeline._attachCameras(cameras, unique);
  59062. };
  59063. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59064. var renderPipeline = this._renderPipelines[renderPipelineName];
  59065. if (!renderPipeline) {
  59066. return;
  59067. }
  59068. renderPipeline._detachCameras(cameras);
  59069. };
  59070. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59071. var renderPipeline = this._renderPipelines[renderPipelineName];
  59072. if (!renderPipeline) {
  59073. return;
  59074. }
  59075. renderPipeline._enableEffect(renderEffectName, cameras);
  59076. };
  59077. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59078. var renderPipeline = this._renderPipelines[renderPipelineName];
  59079. if (!renderPipeline) {
  59080. return;
  59081. }
  59082. renderPipeline._disableEffect(renderEffectName, cameras);
  59083. };
  59084. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59085. var renderPipeline = this._renderPipelines[renderPipelineName];
  59086. if (!renderPipeline) {
  59087. return;
  59088. }
  59089. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59090. };
  59091. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59092. var renderPipeline = this._renderPipelines[renderPipelineName];
  59093. if (!renderPipeline) {
  59094. return;
  59095. }
  59096. renderPipeline._disableDisplayOnlyPass(cameras);
  59097. };
  59098. PostProcessRenderPipelineManager.prototype.update = function () {
  59099. for (var renderPipelineName in this._renderPipelines) {
  59100. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59101. var pipeline = this._renderPipelines[renderPipelineName];
  59102. if (!pipeline.isSupported) {
  59103. pipeline.dispose();
  59104. delete this._renderPipelines[renderPipelineName];
  59105. }
  59106. else {
  59107. pipeline._update();
  59108. }
  59109. }
  59110. }
  59111. };
  59112. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59113. for (var renderPipelineName in this._renderPipelines) {
  59114. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59115. var pipeline = this._renderPipelines[renderPipelineName];
  59116. pipeline._rebuild();
  59117. }
  59118. }
  59119. };
  59120. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59121. for (var renderPipelineName in this._renderPipelines) {
  59122. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59123. var pipeline = this._renderPipelines[renderPipelineName];
  59124. pipeline.dispose();
  59125. }
  59126. }
  59127. };
  59128. return PostProcessRenderPipelineManager;
  59129. }());
  59130. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59131. })(BABYLON || (BABYLON = {}));
  59132. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59133. var BABYLON;
  59134. (function (BABYLON) {
  59135. var PostProcessRenderPass = /** @class */ (function () {
  59136. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59137. this._refCount = 0;
  59138. this._name = name;
  59139. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59140. this.setRenderList(renderList);
  59141. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59142. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59143. this._scene = scene;
  59144. this._renderList = renderList;
  59145. }
  59146. // private
  59147. PostProcessRenderPass.prototype._incRefCount = function () {
  59148. if (this._refCount === 0) {
  59149. this._scene.customRenderTargets.push(this._renderTexture);
  59150. }
  59151. return ++this._refCount;
  59152. };
  59153. PostProcessRenderPass.prototype._decRefCount = function () {
  59154. this._refCount--;
  59155. if (this._refCount <= 0) {
  59156. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59157. }
  59158. return this._refCount;
  59159. };
  59160. PostProcessRenderPass.prototype._update = function () {
  59161. this.setRenderList(this._renderList);
  59162. };
  59163. // public
  59164. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59165. this._renderTexture.renderList = renderList;
  59166. };
  59167. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59168. return this._renderTexture;
  59169. };
  59170. return PostProcessRenderPass;
  59171. }());
  59172. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59173. })(BABYLON || (BABYLON = {}));
  59174. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59175. var BABYLON;
  59176. (function (BABYLON) {
  59177. var PostProcessRenderEffect = /** @class */ (function () {
  59178. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59179. this._name = name;
  59180. this._singleInstance = singleInstance || true;
  59181. this._getPostProcess = getPostProcess;
  59182. this._cameras = {};
  59183. this._indicesForCamera = {};
  59184. this._postProcesses = {};
  59185. this._renderPasses = {};
  59186. this._renderEffectAsPasses = {};
  59187. }
  59188. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59189. get: function () {
  59190. for (var index in this._postProcesses) {
  59191. if (!this._postProcesses[index].isSupported) {
  59192. return false;
  59193. }
  59194. }
  59195. return true;
  59196. },
  59197. enumerable: true,
  59198. configurable: true
  59199. });
  59200. PostProcessRenderEffect.prototype._update = function () {
  59201. for (var renderPassName in this._renderPasses) {
  59202. this._renderPasses[renderPassName]._update();
  59203. }
  59204. };
  59205. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59206. this._renderPasses[renderPass._name] = renderPass;
  59207. this._linkParameters();
  59208. };
  59209. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59210. delete this._renderPasses[renderPass._name];
  59211. this._linkParameters();
  59212. };
  59213. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59214. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59215. this._linkParameters();
  59216. };
  59217. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59218. for (var renderPassName in this._renderPasses) {
  59219. if (renderPassName === passName) {
  59220. return this._renderPasses[passName];
  59221. }
  59222. }
  59223. return null;
  59224. };
  59225. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59226. this._renderPasses = {};
  59227. this._linkParameters();
  59228. };
  59229. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59230. var cameraKey;
  59231. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59232. if (!cams) {
  59233. return;
  59234. }
  59235. for (var i = 0; i < cams.length; i++) {
  59236. var camera = cams[i];
  59237. var cameraName = camera.name;
  59238. if (this._singleInstance) {
  59239. cameraKey = 0;
  59240. }
  59241. else {
  59242. cameraKey = cameraName;
  59243. }
  59244. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59245. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59246. if (!this._indicesForCamera[cameraName]) {
  59247. this._indicesForCamera[cameraName] = [];
  59248. }
  59249. this._indicesForCamera[cameraName].push(index);
  59250. if (!this._cameras[cameraName]) {
  59251. this._cameras[cameraName] = camera;
  59252. }
  59253. for (var passName in this._renderPasses) {
  59254. this._renderPasses[passName]._incRefCount();
  59255. }
  59256. }
  59257. this._linkParameters();
  59258. };
  59259. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59260. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59261. if (!cams) {
  59262. return;
  59263. }
  59264. for (var i = 0; i < cams.length; i++) {
  59265. var camera = cams[i];
  59266. var cameraName = camera.name;
  59267. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59268. if (this._cameras[cameraName]) {
  59269. //this._indicesForCamera.splice(index, 1);
  59270. this._cameras[cameraName] = null;
  59271. }
  59272. for (var passName in this._renderPasses) {
  59273. this._renderPasses[passName]._decRefCount();
  59274. }
  59275. }
  59276. };
  59277. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59278. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59279. if (!cams) {
  59280. return;
  59281. }
  59282. for (var i = 0; i < cams.length; i++) {
  59283. var camera = cams[i];
  59284. var cameraName = camera.name;
  59285. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59286. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59287. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59288. }
  59289. }
  59290. for (var passName in this._renderPasses) {
  59291. this._renderPasses[passName]._incRefCount();
  59292. }
  59293. }
  59294. };
  59295. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59296. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59297. if (!cams) {
  59298. return;
  59299. }
  59300. for (var i = 0; i < cams.length; i++) {
  59301. var camera = cams[i];
  59302. var cameraName = camera.Name;
  59303. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59304. for (var passName in this._renderPasses) {
  59305. this._renderPasses[passName]._decRefCount();
  59306. }
  59307. }
  59308. };
  59309. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59310. if (this._singleInstance) {
  59311. return this._postProcesses[0];
  59312. }
  59313. else {
  59314. if (!camera) {
  59315. return null;
  59316. }
  59317. return this._postProcesses[camera.name];
  59318. }
  59319. };
  59320. PostProcessRenderEffect.prototype._linkParameters = function () {
  59321. var _this = this;
  59322. for (var index in this._postProcesses) {
  59323. if (this.applyParameters) {
  59324. this.applyParameters(this._postProcesses[index]);
  59325. }
  59326. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59327. _this._linkTextures(effect);
  59328. });
  59329. }
  59330. };
  59331. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59332. for (var renderPassName in this._renderPasses) {
  59333. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59334. }
  59335. for (var renderEffectName in this._renderEffectAsPasses) {
  59336. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59337. }
  59338. };
  59339. return PostProcessRenderEffect;
  59340. }());
  59341. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59342. })(BABYLON || (BABYLON = {}));
  59343. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59344. var BABYLON;
  59345. (function (BABYLON) {
  59346. var PostProcessRenderPipeline = /** @class */ (function () {
  59347. function PostProcessRenderPipeline(engine, name) {
  59348. this._engine = engine;
  59349. this._name = name;
  59350. this._renderEffects = {};
  59351. this._renderEffectsForIsolatedPass = new Array();
  59352. this._cameras = [];
  59353. }
  59354. PostProcessRenderPipeline.prototype.getClassName = function () {
  59355. return "PostProcessRenderPipeline";
  59356. };
  59357. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59358. get: function () {
  59359. for (var renderEffectName in this._renderEffects) {
  59360. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59361. if (!this._renderEffects[renderEffectName].isSupported) {
  59362. return false;
  59363. }
  59364. }
  59365. }
  59366. return true;
  59367. },
  59368. enumerable: true,
  59369. configurable: true
  59370. });
  59371. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59372. this._renderEffects[renderEffect._name] = renderEffect;
  59373. };
  59374. // private
  59375. PostProcessRenderPipeline.prototype._rebuild = function () {
  59376. };
  59377. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59378. var renderEffects = this._renderEffects[renderEffectName];
  59379. if (!renderEffects) {
  59380. return;
  59381. }
  59382. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59383. };
  59384. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59385. var renderEffects = this._renderEffects[renderEffectName];
  59386. if (!renderEffects) {
  59387. return;
  59388. }
  59389. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59390. };
  59391. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59392. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59393. if (!cams) {
  59394. return;
  59395. }
  59396. var indicesToDelete = [];
  59397. var i;
  59398. for (i = 0; i < cams.length; i++) {
  59399. var camera = cams[i];
  59400. var cameraName = camera.name;
  59401. if (this._cameras.indexOf(camera) === -1) {
  59402. this._cameras[cameraName] = camera;
  59403. }
  59404. else if (unique) {
  59405. indicesToDelete.push(i);
  59406. }
  59407. }
  59408. for (i = 0; i < indicesToDelete.length; i++) {
  59409. cameras.splice(indicesToDelete[i], 1);
  59410. }
  59411. for (var renderEffectName in this._renderEffects) {
  59412. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59413. this._renderEffects[renderEffectName]._attachCameras(cams);
  59414. }
  59415. }
  59416. };
  59417. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59418. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59419. if (!cams) {
  59420. return;
  59421. }
  59422. for (var renderEffectName in this._renderEffects) {
  59423. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59424. this._renderEffects[renderEffectName]._detachCameras(cams);
  59425. }
  59426. }
  59427. for (var i = 0; i < cams.length; i++) {
  59428. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59429. }
  59430. };
  59431. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59432. var _this = this;
  59433. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59434. if (!cams) {
  59435. return;
  59436. }
  59437. var pass = null;
  59438. var renderEffectName;
  59439. for (renderEffectName in this._renderEffects) {
  59440. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59441. pass = this._renderEffects[renderEffectName].getPass(passName);
  59442. if (pass != null) {
  59443. break;
  59444. }
  59445. }
  59446. }
  59447. if (pass === null) {
  59448. return;
  59449. }
  59450. for (renderEffectName in this._renderEffects) {
  59451. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59452. this._renderEffects[renderEffectName]._disable(cams);
  59453. }
  59454. }
  59455. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59456. for (var i = 0; i < cams.length; i++) {
  59457. var camera = cams[i];
  59458. var cameraName = camera.name;
  59459. 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); });
  59460. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59461. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59462. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59463. }
  59464. };
  59465. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59466. var _this = this;
  59467. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59468. if (!cams) {
  59469. return;
  59470. }
  59471. for (var i = 0; i < cams.length; i++) {
  59472. var camera = cams[i];
  59473. var cameraName = camera.name;
  59474. 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); });
  59475. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59476. }
  59477. for (var renderEffectName in this._renderEffects) {
  59478. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59479. this._renderEffects[renderEffectName]._enable(cams);
  59480. }
  59481. }
  59482. };
  59483. PostProcessRenderPipeline.prototype._update = function () {
  59484. for (var renderEffectName in this._renderEffects) {
  59485. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59486. this._renderEffects[renderEffectName]._update();
  59487. }
  59488. }
  59489. for (var i = 0; i < this._cameras.length; i++) {
  59490. var cameraName = this._cameras[i].name;
  59491. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59492. this._renderEffectsForIsolatedPass[cameraName]._update();
  59493. }
  59494. }
  59495. };
  59496. PostProcessRenderPipeline.prototype._reset = function () {
  59497. this._renderEffects = {};
  59498. this._renderEffectsForIsolatedPass = new Array();
  59499. };
  59500. PostProcessRenderPipeline.prototype.dispose = function () {
  59501. // Must be implemented by children
  59502. };
  59503. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59504. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59505. __decorate([
  59506. BABYLON.serialize()
  59507. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59508. return PostProcessRenderPipeline;
  59509. }());
  59510. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59511. })(BABYLON || (BABYLON = {}));
  59512. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59513. var BABYLON;
  59514. (function (BABYLON) {
  59515. var DepthRenderer = /** @class */ (function () {
  59516. function DepthRenderer(scene, type) {
  59517. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59518. var _this = this;
  59519. this._scene = scene;
  59520. var engine = scene.getEngine();
  59521. // Render target
  59522. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59523. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59524. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59525. this._depthMap.refreshRate = 1;
  59526. this._depthMap.renderParticles = false;
  59527. this._depthMap.renderList = null;
  59528. // set default depth value to 1.0 (far away)
  59529. this._depthMap.onClearObservable.add(function (engine) {
  59530. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59531. });
  59532. // Custom render function
  59533. var renderSubMesh = function (subMesh) {
  59534. var mesh = subMesh.getRenderingMesh();
  59535. var scene = _this._scene;
  59536. var engine = scene.getEngine();
  59537. var material = subMesh.getMaterial();
  59538. if (!material) {
  59539. return;
  59540. }
  59541. // Culling and reverse (right handed system)
  59542. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59543. // Managing instances
  59544. var batch = mesh._getInstancesRenderList(subMesh._id);
  59545. if (batch.mustReturn) {
  59546. return;
  59547. }
  59548. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59549. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59550. engine.enableEffect(_this._effect);
  59551. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59552. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59553. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59554. // Alpha test
  59555. if (material && material.needAlphaTesting()) {
  59556. var alphaTexture = material.getAlphaTestTexture();
  59557. if (alphaTexture) {
  59558. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59559. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59560. }
  59561. }
  59562. // Bones
  59563. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59564. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59565. }
  59566. // Draw
  59567. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59568. }
  59569. };
  59570. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59571. var index;
  59572. if (depthOnlySubMeshes.length) {
  59573. engine.setColorWrite(false);
  59574. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59575. renderSubMesh(depthOnlySubMeshes.data[index]);
  59576. }
  59577. engine.setColorWrite(true);
  59578. }
  59579. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59580. renderSubMesh(opaqueSubMeshes.data[index]);
  59581. }
  59582. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59583. renderSubMesh(alphaTestSubMeshes.data[index]);
  59584. }
  59585. };
  59586. }
  59587. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59588. var material = subMesh.getMaterial();
  59589. if (material.disableDepthWrite) {
  59590. return false;
  59591. }
  59592. var defines = [];
  59593. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59594. var mesh = subMesh.getMesh();
  59595. // Alpha test
  59596. if (material && material.needAlphaTesting()) {
  59597. defines.push("#define ALPHATEST");
  59598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59599. attribs.push(BABYLON.VertexBuffer.UVKind);
  59600. defines.push("#define UV1");
  59601. }
  59602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59603. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59604. defines.push("#define UV2");
  59605. }
  59606. }
  59607. // Bones
  59608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59611. if (mesh.numBoneInfluencers > 4) {
  59612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59614. }
  59615. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59616. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59617. }
  59618. else {
  59619. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59620. }
  59621. // Instances
  59622. if (useInstances) {
  59623. defines.push("#define INSTANCES");
  59624. attribs.push("world0");
  59625. attribs.push("world1");
  59626. attribs.push("world2");
  59627. attribs.push("world3");
  59628. }
  59629. // Get correct effect
  59630. var join = defines.join("\n");
  59631. if (this._cachedDefines !== join) {
  59632. this._cachedDefines = join;
  59633. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59634. }
  59635. return this._effect.isReady();
  59636. };
  59637. DepthRenderer.prototype.getDepthMap = function () {
  59638. return this._depthMap;
  59639. };
  59640. // Methods
  59641. DepthRenderer.prototype.dispose = function () {
  59642. this._depthMap.dispose();
  59643. };
  59644. return DepthRenderer;
  59645. }());
  59646. BABYLON.DepthRenderer = DepthRenderer;
  59647. })(BABYLON || (BABYLON = {}));
  59648. //# sourceMappingURL=babylon.depthRenderer.js.map
  59649. var BABYLON;
  59650. (function (BABYLON) {
  59651. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59652. __extends(SSAORenderingPipeline, _super);
  59653. /**
  59654. * @constructor
  59655. * @param {string} name - The rendering pipeline name
  59656. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59657. * @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 }
  59658. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59659. */
  59660. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59661. var _this = _super.call(this, scene.getEngine(), name) || this;
  59662. // Members
  59663. /**
  59664. * The PassPostProcess id in the pipeline that contains the original scene color
  59665. * @type {string}
  59666. */
  59667. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59668. /**
  59669. * The SSAO PostProcess id in the pipeline
  59670. * @type {string}
  59671. */
  59672. _this.SSAORenderEffect = "SSAORenderEffect";
  59673. /**
  59674. * The horizontal blur PostProcess id in the pipeline
  59675. * @type {string}
  59676. */
  59677. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59678. /**
  59679. * The vertical blur PostProcess id in the pipeline
  59680. * @type {string}
  59681. */
  59682. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59683. /**
  59684. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59685. * @type {string}
  59686. */
  59687. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59688. /**
  59689. * The output strength of the SSAO post-process. Default value is 1.0.
  59690. * @type {number}
  59691. */
  59692. _this.totalStrength = 1.0;
  59693. /**
  59694. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  59695. * @type {number}
  59696. */
  59697. _this.radius = 0.0001;
  59698. /**
  59699. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  59700. * Must not be equal to fallOff and superior to fallOff.
  59701. * Default value is 0.975
  59702. * @type {number}
  59703. */
  59704. _this.area = 0.0075;
  59705. /**
  59706. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  59707. * Must not be equal to area and inferior to area.
  59708. * Default value is 0.0
  59709. * @type {number}
  59710. */
  59711. _this.fallOff = 0.000001;
  59712. /**
  59713. * The base color of the SSAO post-process
  59714. * The final result is "base + ssao" between [0, 1]
  59715. * @type {number}
  59716. */
  59717. _this.base = 0.5;
  59718. _this._firstUpdate = true;
  59719. _this._scene = scene;
  59720. // Set up assets
  59721. _this._createRandomTexture();
  59722. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59723. var ssaoRatio = ratio.ssaoRatio || ratio;
  59724. var combineRatio = ratio.combineRatio || ratio;
  59725. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59726. _this._createSSAOPostProcess(ssaoRatio);
  59727. _this._createBlurPostProcess(ssaoRatio);
  59728. _this._createSSAOCombinePostProcess(combineRatio);
  59729. // Set up pipeline
  59730. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59731. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59732. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59733. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59734. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59735. // Finish
  59736. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59737. if (cameras)
  59738. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59739. return _this;
  59740. }
  59741. // Public Methods
  59742. /**
  59743. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59744. */
  59745. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59746. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59747. for (var i = 0; i < this._scene.cameras.length; i++) {
  59748. var camera = this._scene.cameras[i];
  59749. this._originalColorPostProcess.dispose(camera);
  59750. this._ssaoPostProcess.dispose(camera);
  59751. this._blurHPostProcess.dispose(camera);
  59752. this._blurVPostProcess.dispose(camera);
  59753. this._ssaoCombinePostProcess.dispose(camera);
  59754. }
  59755. this._randomTexture.dispose();
  59756. if (disableDepthRender)
  59757. this._scene.disableDepthRenderer();
  59758. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59759. _super.prototype.dispose.call(this);
  59760. };
  59761. // Private Methods
  59762. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  59763. var _this = this;
  59764. var size = 16;
  59765. 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);
  59766. 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);
  59767. this._blurHPostProcess.onActivateObservable.add(function () {
  59768. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  59769. _this._blurHPostProcess.kernel = size * dw;
  59770. });
  59771. this._blurVPostProcess.onActivateObservable.add(function () {
  59772. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  59773. _this._blurVPostProcess.kernel = size * dw;
  59774. });
  59775. };
  59776. SSAORenderingPipeline.prototype._rebuild = function () {
  59777. this._firstUpdate = true;
  59778. _super.prototype._rebuild.call(this);
  59779. };
  59780. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59781. var _this = this;
  59782. var numSamples = 16;
  59783. var sampleSphere = [
  59784. 0.5381, 0.1856, -0.4319,
  59785. 0.1379, 0.2486, 0.4430,
  59786. 0.3371, 0.5679, -0.0057,
  59787. -0.6999, -0.0451, -0.0019,
  59788. 0.0689, -0.1598, -0.8547,
  59789. 0.0560, 0.0069, -0.1843,
  59790. -0.0146, 0.1402, 0.0762,
  59791. 0.0100, -0.1924, -0.0344,
  59792. -0.3577, -0.5301, -0.4358,
  59793. -0.3169, 0.1063, 0.0158,
  59794. 0.0103, -0.5869, 0.0046,
  59795. -0.0897, -0.4940, 0.3287,
  59796. 0.7119, -0.0154, -0.0918,
  59797. -0.0533, 0.0596, -0.5411,
  59798. 0.0352, -0.0631, 0.5460,
  59799. -0.4776, 0.2847, -0.0271
  59800. ];
  59801. var samplesFactor = 1.0 / numSamples;
  59802. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  59803. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59804. "area", "fallOff", "base", "range", "viewport"
  59805. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59806. this._ssaoPostProcess.onApply = function (effect) {
  59807. if (_this._firstUpdate) {
  59808. effect.setArray3("sampleSphere", sampleSphere);
  59809. effect.setFloat("samplesFactor", samplesFactor);
  59810. effect.setFloat("randTextureTiles", 4.0);
  59811. }
  59812. effect.setFloat("totalStrength", _this.totalStrength);
  59813. effect.setFloat("radius", _this.radius);
  59814. effect.setFloat("area", _this.area);
  59815. effect.setFloat("fallOff", _this.fallOff);
  59816. effect.setFloat("base", _this.base);
  59817. effect.setTexture("textureSampler", _this._depthTexture);
  59818. effect.setTexture("randomSampler", _this._randomTexture);
  59819. };
  59820. };
  59821. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59822. var _this = this;
  59823. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59824. this._ssaoCombinePostProcess.onApply = function (effect) {
  59825. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59826. };
  59827. };
  59828. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  59829. var size = 512;
  59830. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59831. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59832. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59833. var context = this._randomTexture.getContext();
  59834. var rand = function (min, max) {
  59835. return Math.random() * (max - min) + min;
  59836. };
  59837. var randVector = BABYLON.Vector3.Zero();
  59838. for (var x = 0; x < size; x++) {
  59839. for (var y = 0; y < size; y++) {
  59840. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  59841. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  59842. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  59843. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59844. context.fillRect(x, y, 1, 1);
  59845. }
  59846. }
  59847. this._randomTexture.update(false);
  59848. };
  59849. __decorate([
  59850. BABYLON.serialize()
  59851. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  59852. __decorate([
  59853. BABYLON.serialize()
  59854. ], SSAORenderingPipeline.prototype, "radius", void 0);
  59855. __decorate([
  59856. BABYLON.serialize()
  59857. ], SSAORenderingPipeline.prototype, "area", void 0);
  59858. __decorate([
  59859. BABYLON.serialize()
  59860. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  59861. __decorate([
  59862. BABYLON.serialize()
  59863. ], SSAORenderingPipeline.prototype, "base", void 0);
  59864. return SSAORenderingPipeline;
  59865. }(BABYLON.PostProcessRenderPipeline));
  59866. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  59867. })(BABYLON || (BABYLON = {}));
  59868. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  59869. var BABYLON;
  59870. (function (BABYLON) {
  59871. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  59872. __extends(SSAO2RenderingPipeline, _super);
  59873. /**
  59874. * @constructor
  59875. * @param {string} name - The rendering pipeline name
  59876. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59877. * @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 }
  59878. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59879. */
  59880. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  59881. var _this = _super.call(this, scene.getEngine(), name) || this;
  59882. // Members
  59883. /**
  59884. * The PassPostProcess id in the pipeline that contains the original scene color
  59885. * @type {string}
  59886. */
  59887. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59888. /**
  59889. * The SSAO PostProcess id in the pipeline
  59890. * @type {string}
  59891. */
  59892. _this.SSAORenderEffect = "SSAORenderEffect";
  59893. /**
  59894. * The horizontal blur PostProcess id in the pipeline
  59895. * @type {string}
  59896. */
  59897. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59898. /**
  59899. * The vertical blur PostProcess id in the pipeline
  59900. * @type {string}
  59901. */
  59902. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59903. /**
  59904. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59905. * @type {string}
  59906. */
  59907. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59908. /**
  59909. * The output strength of the SSAO post-process. Default value is 1.0.
  59910. * @type {number}
  59911. */
  59912. _this.totalStrength = 1.0;
  59913. /**
  59914. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  59915. * @type {number}
  59916. */
  59917. _this.maxZ = 100.0;
  59918. /**
  59919. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  59920. * @type {number}
  59921. */
  59922. _this.minZAspect = 0.2;
  59923. /**
  59924. * Number of samples used for the SSAO calculations. Default value is 8
  59925. * @type {number}
  59926. */
  59927. _this._samples = 8;
  59928. /**
  59929. * Are we using bilateral blur ?
  59930. * @type {boolean}
  59931. */
  59932. _this._expensiveBlur = true;
  59933. /**
  59934. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  59935. * @type {number}
  59936. */
  59937. _this.radius = 2.0;
  59938. /**
  59939. * The base color of the SSAO post-process
  59940. * The final result is "base + ssao" between [0, 1]
  59941. * @type {number}
  59942. */
  59943. _this.base = 0.1;
  59944. _this._firstUpdate = true;
  59945. _this._scene = scene;
  59946. if (!_this.isSupported) {
  59947. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  59948. return _this;
  59949. }
  59950. var ssaoRatio = ratio.ssaoRatio || ratio;
  59951. var blurRatio = ratio.blurRatio || ratio;
  59952. // Set up assets
  59953. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  59954. _this._createRandomTexture();
  59955. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  59956. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  59957. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59958. _this._createSSAOPostProcess(1.0);
  59959. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  59960. _this._createSSAOCombinePostProcess(blurRatio);
  59961. // Set up pipeline
  59962. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59963. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59964. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59965. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59966. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59967. // Finish
  59968. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59969. if (cameras)
  59970. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59971. return _this;
  59972. }
  59973. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  59974. get: function () {
  59975. return this._samples;
  59976. },
  59977. set: function (n) {
  59978. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  59979. this._samples = n;
  59980. this._sampleSphere = this._generateHemisphere();
  59981. this._firstUpdate = true;
  59982. },
  59983. enumerable: true,
  59984. configurable: true
  59985. });
  59986. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  59987. get: function () {
  59988. return this._expensiveBlur;
  59989. },
  59990. set: function (b) {
  59991. 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"]);
  59992. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  59993. this._expensiveBlur = b;
  59994. this._firstUpdate = true;
  59995. },
  59996. enumerable: true,
  59997. configurable: true
  59998. });
  59999. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60000. /**
  60001. * Support test.
  60002. * @type {boolean}
  60003. */
  60004. get: function () {
  60005. var engine = BABYLON.Engine.LastCreatedEngine;
  60006. if (!engine) {
  60007. return false;
  60008. }
  60009. return engine.getCaps().drawBuffersExtension;
  60010. },
  60011. enumerable: true,
  60012. configurable: true
  60013. });
  60014. // Public Methods
  60015. /**
  60016. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60017. */
  60018. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60019. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60020. for (var i = 0; i < this._scene.cameras.length; i++) {
  60021. var camera = this._scene.cameras[i];
  60022. this._originalColorPostProcess.dispose(camera);
  60023. this._ssaoPostProcess.dispose(camera);
  60024. this._blurHPostProcess.dispose(camera);
  60025. this._blurVPostProcess.dispose(camera);
  60026. this._ssaoCombinePostProcess.dispose(camera);
  60027. }
  60028. this._randomTexture.dispose();
  60029. if (disableGeometryBufferRenderer)
  60030. this._scene.disableGeometryBufferRenderer();
  60031. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60032. _super.prototype.dispose.call(this);
  60033. };
  60034. // Private Methods
  60035. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60036. var _this = this;
  60037. this._samplerOffsets = [];
  60038. var expensive = this.expensiveBlur;
  60039. for (var i = -8; i < 8; i++) {
  60040. this._samplerOffsets.push(i * 2 + 0.5);
  60041. }
  60042. 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");
  60043. this._blurHPostProcess.onApply = function (effect) {
  60044. if (!_this._scene.activeCamera) {
  60045. return;
  60046. }
  60047. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60048. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60049. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60050. effect.setFloat("radius", _this.radius);
  60051. effect.setTexture("depthSampler", _this._depthTexture);
  60052. if (_this._firstUpdate) {
  60053. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60054. }
  60055. };
  60056. 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");
  60057. this._blurVPostProcess.onApply = function (effect) {
  60058. if (!_this._scene.activeCamera) {
  60059. return;
  60060. }
  60061. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60062. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60063. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60064. effect.setFloat("radius", _this.radius);
  60065. effect.setTexture("depthSampler", _this._depthTexture);
  60066. if (_this._firstUpdate) {
  60067. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60068. _this._firstUpdate = false;
  60069. }
  60070. };
  60071. };
  60072. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60073. this._firstUpdate = true;
  60074. _super.prototype._rebuild.call(this);
  60075. };
  60076. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60077. var numSamples = this.samples;
  60078. var result = [];
  60079. var vector, scale;
  60080. var rand = function (min, max) {
  60081. return Math.random() * (max - min) + min;
  60082. };
  60083. var i = 0;
  60084. while (i < numSamples) {
  60085. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60086. vector.normalize();
  60087. scale = i / numSamples;
  60088. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60089. vector.scaleInPlace(scale);
  60090. result.push(vector.x, vector.y, vector.z);
  60091. i++;
  60092. }
  60093. return result;
  60094. };
  60095. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60096. var _this = this;
  60097. var numSamples = this.samples;
  60098. this._sampleSphere = this._generateHemisphere();
  60099. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60100. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60101. "base", "range", "projection", "near", "far", "texelSize",
  60102. "xViewport", "yViewport", "maxZ", "minZAspect"
  60103. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60104. this._ssaoPostProcess.onApply = function (effect) {
  60105. if (_this._firstUpdate) {
  60106. effect.setArray3("sampleSphere", _this._sampleSphere);
  60107. effect.setFloat("randTextureTiles", 4.0);
  60108. }
  60109. if (!_this._scene.activeCamera) {
  60110. return;
  60111. }
  60112. effect.setFloat("samplesFactor", 1 / _this.samples);
  60113. effect.setFloat("totalStrength", _this.totalStrength);
  60114. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60115. effect.setFloat("radius", _this.radius);
  60116. effect.setFloat("maxZ", _this.maxZ);
  60117. effect.setFloat("minZAspect", _this.minZAspect);
  60118. effect.setFloat("base", _this.base);
  60119. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60120. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60121. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60122. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60123. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60124. effect.setTexture("textureSampler", _this._depthTexture);
  60125. effect.setTexture("normalSampler", _this._normalTexture);
  60126. effect.setTexture("randomSampler", _this._randomTexture);
  60127. };
  60128. };
  60129. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60130. var _this = this;
  60131. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60132. this._ssaoCombinePostProcess.onApply = function (effect) {
  60133. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60134. };
  60135. };
  60136. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60137. var size = 512;
  60138. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60139. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60140. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60141. var context = this._randomTexture.getContext();
  60142. var rand = function (min, max) {
  60143. return Math.random() * (max - min) + min;
  60144. };
  60145. var randVector = BABYLON.Vector3.Zero();
  60146. for (var x = 0; x < size; x++) {
  60147. for (var y = 0; y < size; y++) {
  60148. randVector.x = rand(0.0, 1.0);
  60149. randVector.y = rand(0.0, 1.0);
  60150. randVector.z = 0.0;
  60151. randVector.normalize();
  60152. randVector.scaleInPlace(255);
  60153. randVector.x = Math.floor(randVector.x);
  60154. randVector.y = Math.floor(randVector.y);
  60155. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60156. context.fillRect(x, y, 1, 1);
  60157. }
  60158. }
  60159. this._randomTexture.update(false);
  60160. };
  60161. __decorate([
  60162. BABYLON.serialize()
  60163. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60164. __decorate([
  60165. BABYLON.serialize()
  60166. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60167. __decorate([
  60168. BABYLON.serialize()
  60169. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60170. __decorate([
  60171. BABYLON.serialize("samples")
  60172. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60173. __decorate([
  60174. BABYLON.serialize("expensiveBlur")
  60175. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60176. __decorate([
  60177. BABYLON.serialize()
  60178. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60179. __decorate([
  60180. BABYLON.serialize()
  60181. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60182. return SSAO2RenderingPipeline;
  60183. }(BABYLON.PostProcessRenderPipeline));
  60184. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60185. })(BABYLON || (BABYLON = {}));
  60186. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60187. // BABYLON.JS Chromatic Aberration GLSL Shader
  60188. // Author: Olivier Guyot
  60189. // Separates very slightly R, G and B colors on the edges of the screen
  60190. // Inspired by Francois Tarlier & Martins Upitis
  60191. var BABYLON;
  60192. (function (BABYLON) {
  60193. var LensRenderingPipeline = /** @class */ (function (_super) {
  60194. __extends(LensRenderingPipeline, _super);
  60195. /**
  60196. * @constructor
  60197. *
  60198. * Effect parameters are as follow:
  60199. * {
  60200. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60201. * edge_blur: number; // from 0 to x (1 for realism)
  60202. * distortion: number; // from 0 to x (1 for realism)
  60203. * grain_amount: number; // from 0 to 1
  60204. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60205. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60206. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60207. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60208. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60209. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60210. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60211. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60212. * }
  60213. * Note: if an effect parameter is unset, effect is disabled
  60214. *
  60215. * @param {string} name - The rendering pipeline name
  60216. * @param {object} parameters - An object containing all parameters (see above)
  60217. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60218. * @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)
  60219. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60220. */
  60221. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60222. if (ratio === void 0) { ratio = 1.0; }
  60223. var _this = _super.call(this, scene.getEngine(), name) || this;
  60224. // Lens effects can be of the following:
  60225. // - chromatic aberration (slight shift of RGB colors)
  60226. // - blur on the edge of the lens
  60227. // - lens distortion
  60228. // - depth-of-field blur & highlights enhancing
  60229. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60230. // - grain effect (noise or custom texture)
  60231. // Two additional texture samplers are needed:
  60232. // - depth map (for depth-of-field)
  60233. // - grain texture
  60234. /**
  60235. * The chromatic aberration PostProcess id in the pipeline
  60236. * @type {string}
  60237. */
  60238. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60239. /**
  60240. * The highlights enhancing PostProcess id in the pipeline
  60241. * @type {string}
  60242. */
  60243. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60244. /**
  60245. * The depth-of-field PostProcess id in the pipeline
  60246. * @type {string}
  60247. */
  60248. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60249. _this._scene = scene;
  60250. // Fetch texture samplers
  60251. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60252. if (parameters.grain_texture) {
  60253. _this._grainTexture = parameters.grain_texture;
  60254. }
  60255. else {
  60256. _this._createGrainTexture();
  60257. }
  60258. // save parameters
  60259. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60260. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60261. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60262. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60263. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60264. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60265. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60266. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60267. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60268. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60269. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60270. // Create effects
  60271. _this._createChromaticAberrationPostProcess(ratio);
  60272. _this._createHighlightsPostProcess(ratio);
  60273. _this._createDepthOfFieldPostProcess(ratio / 4);
  60274. // Set up pipeline
  60275. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60276. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60278. if (_this._highlightsGain === -1) {
  60279. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60280. }
  60281. // Finish
  60282. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60283. if (cameras) {
  60284. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60285. }
  60286. return _this;
  60287. }
  60288. // public methods (self explanatory)
  60289. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60290. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60291. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60292. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60293. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60294. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60295. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60296. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60297. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60298. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60299. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60300. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60301. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60302. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60303. };
  60304. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60305. this._highlightsPostProcess.updateEffect();
  60306. };
  60307. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60308. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60309. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60310. this._highlightsGain = amount;
  60311. };
  60312. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60313. if (this._highlightsGain === -1) {
  60314. this._highlightsGain = 1.0;
  60315. }
  60316. this._highlightsThreshold = amount;
  60317. };
  60318. LensRenderingPipeline.prototype.disableHighlights = function () {
  60319. this._highlightsGain = -1;
  60320. };
  60321. /**
  60322. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60323. */
  60324. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60325. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60326. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60327. this._chromaticAberrationPostProcess = null;
  60328. this._highlightsPostProcess = null;
  60329. this._depthOfFieldPostProcess = null;
  60330. this._grainTexture.dispose();
  60331. if (disableDepthRender)
  60332. this._scene.disableDepthRenderer();
  60333. };
  60334. // colors shifting and distortion
  60335. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60336. var _this = this;
  60337. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60338. [], // samplers
  60339. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60340. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60341. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60342. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60343. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60344. };
  60345. };
  60346. // highlights enhancing
  60347. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60348. var _this = this;
  60349. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60350. [], // samplers
  60351. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60352. this._highlightsPostProcess.onApply = function (effect) {
  60353. effect.setFloat('gain', _this._highlightsGain);
  60354. effect.setFloat('threshold', _this._highlightsThreshold);
  60355. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60356. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60357. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60358. };
  60359. };
  60360. // colors shifting and distortion
  60361. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60362. var _this = this;
  60363. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60364. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60365. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60366. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60367. this._depthOfFieldPostProcess.onApply = function (effect) {
  60368. effect.setTexture("depthSampler", _this._depthTexture);
  60369. effect.setTexture("grainSampler", _this._grainTexture);
  60370. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60371. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60372. effect.setFloat('grain_amount', _this._grainAmount);
  60373. effect.setBool('blur_noise', _this._blurNoise);
  60374. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60375. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60376. effect.setFloat('distortion', _this._distortion);
  60377. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60378. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60379. effect.setFloat('aperture', _this._dofAperture);
  60380. effect.setFloat('darken', _this._dofDarken);
  60381. effect.setFloat('edge_blur', _this._edgeBlur);
  60382. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60383. if (_this._scene.activeCamera) {
  60384. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60385. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60386. }
  60387. };
  60388. };
  60389. // creates a black and white random noise texture, 512x512
  60390. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60391. var size = 512;
  60392. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60393. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60394. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60395. var context = this._grainTexture.getContext();
  60396. var rand = function (min, max) {
  60397. return Math.random() * (max - min) + min;
  60398. };
  60399. var value;
  60400. for (var x = 0; x < size; x++) {
  60401. for (var y = 0; y < size; y++) {
  60402. value = Math.floor(rand(0.42, 0.58) * 255);
  60403. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60404. context.fillRect(x, y, 1, 1);
  60405. }
  60406. }
  60407. this._grainTexture.update(false);
  60408. };
  60409. return LensRenderingPipeline;
  60410. }(BABYLON.PostProcessRenderPipeline));
  60411. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60412. })(BABYLON || (BABYLON = {}));
  60413. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60414. var BABYLON;
  60415. (function (BABYLON) {
  60416. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60417. __extends(StandardRenderingPipeline, _super);
  60418. /**
  60419. * @constructor
  60420. * @param {string} name - The rendering pipeline name
  60421. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60422. * @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)
  60423. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60424. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60425. */
  60426. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60427. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60428. var _this = _super.call(this, scene.getEngine(), name) || this;
  60429. _this.downSampleX4PostProcess = null;
  60430. _this.brightPassPostProcess = null;
  60431. _this.blurHPostProcesses = [];
  60432. _this.blurVPostProcesses = [];
  60433. _this.textureAdderPostProcess = null;
  60434. _this.volumetricLightPostProcess = null;
  60435. _this.volumetricLightSmoothXPostProcess = null;
  60436. _this.volumetricLightSmoothYPostProcess = null;
  60437. _this.volumetricLightMergePostProces = null;
  60438. _this.volumetricLightFinalPostProcess = null;
  60439. _this.luminancePostProcess = null;
  60440. _this.luminanceDownSamplePostProcesses = [];
  60441. _this.hdrPostProcess = null;
  60442. _this.textureAdderFinalPostProcess = null;
  60443. _this.lensFlareFinalPostProcess = null;
  60444. _this.hdrFinalPostProcess = null;
  60445. _this.lensFlarePostProcess = null;
  60446. _this.lensFlareComposePostProcess = null;
  60447. _this.motionBlurPostProcess = null;
  60448. _this.depthOfFieldPostProcess = null;
  60449. // Values
  60450. _this.brightThreshold = 1.0;
  60451. _this.blurWidth = 512.0;
  60452. _this.horizontalBlur = false;
  60453. _this.exposure = 1.0;
  60454. _this.lensTexture = null;
  60455. _this.volumetricLightCoefficient = 0.2;
  60456. _this.volumetricLightPower = 4.0;
  60457. _this.volumetricLightBlurScale = 64.0;
  60458. _this.sourceLight = null;
  60459. _this.hdrMinimumLuminance = 1.0;
  60460. _this.hdrDecreaseRate = 0.5;
  60461. _this.hdrIncreaseRate = 0.5;
  60462. _this.lensColorTexture = null;
  60463. _this.lensFlareStrength = 20.0;
  60464. _this.lensFlareGhostDispersal = 1.4;
  60465. _this.lensFlareHaloWidth = 0.7;
  60466. _this.lensFlareDistortionStrength = 16.0;
  60467. _this.lensStarTexture = null;
  60468. _this.lensFlareDirtTexture = null;
  60469. _this.depthOfFieldDistance = 10.0;
  60470. _this.depthOfFieldBlurWidth = 64.0;
  60471. _this.motionStrength = 1.0;
  60472. // IAnimatable
  60473. _this.animations = [];
  60474. _this._currentDepthOfFieldSource = null;
  60475. _this._hdrCurrentLuminance = 1.0;
  60476. // Getters and setters
  60477. _this._bloomEnabled = true;
  60478. _this._depthOfFieldEnabled = false;
  60479. _this._vlsEnabled = false;
  60480. _this._lensFlareEnabled = false;
  60481. _this._hdrEnabled = false;
  60482. _this._motionBlurEnabled = false;
  60483. _this._motionBlurSamples = 64.0;
  60484. _this._volumetricLightStepsCount = 50.0;
  60485. _this._cameras = cameras || [];
  60486. // Initialize
  60487. _this._scene = scene;
  60488. _this._basePostProcess = originalPostProcess;
  60489. _this._ratio = ratio;
  60490. // Misc
  60491. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60492. // Finish
  60493. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60494. _this._buildPipeline();
  60495. return _this;
  60496. }
  60497. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60498. get: function () {
  60499. return this._bloomEnabled;
  60500. },
  60501. set: function (enabled) {
  60502. if (this._bloomEnabled === enabled) {
  60503. return;
  60504. }
  60505. this._bloomEnabled = enabled;
  60506. this._buildPipeline();
  60507. },
  60508. enumerable: true,
  60509. configurable: true
  60510. });
  60511. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60512. get: function () {
  60513. return this._depthOfFieldEnabled;
  60514. },
  60515. set: function (enabled) {
  60516. if (this._depthOfFieldEnabled === enabled) {
  60517. return;
  60518. }
  60519. this._depthOfFieldEnabled = enabled;
  60520. this._buildPipeline();
  60521. },
  60522. enumerable: true,
  60523. configurable: true
  60524. });
  60525. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60526. get: function () {
  60527. return this._lensFlareEnabled;
  60528. },
  60529. set: function (enabled) {
  60530. if (this._lensFlareEnabled === enabled) {
  60531. return;
  60532. }
  60533. this._lensFlareEnabled = enabled;
  60534. this._buildPipeline();
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60540. get: function () {
  60541. return this._hdrEnabled;
  60542. },
  60543. set: function (enabled) {
  60544. if (this._hdrEnabled === enabled) {
  60545. return;
  60546. }
  60547. this._hdrEnabled = enabled;
  60548. this._buildPipeline();
  60549. },
  60550. enumerable: true,
  60551. configurable: true
  60552. });
  60553. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60554. get: function () {
  60555. return this._vlsEnabled;
  60556. },
  60557. set: function (enabled) {
  60558. if (this._vlsEnabled === enabled) {
  60559. return;
  60560. }
  60561. if (enabled) {
  60562. var geometry = this._scene.enableGeometryBufferRenderer();
  60563. if (!geometry) {
  60564. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60565. return;
  60566. }
  60567. }
  60568. this._vlsEnabled = enabled;
  60569. this._buildPipeline();
  60570. },
  60571. enumerable: true,
  60572. configurable: true
  60573. });
  60574. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60575. get: function () {
  60576. return this._motionBlurEnabled;
  60577. },
  60578. set: function (enabled) {
  60579. if (this._motionBlurEnabled === enabled) {
  60580. return;
  60581. }
  60582. this._motionBlurEnabled = enabled;
  60583. this._buildPipeline();
  60584. },
  60585. enumerable: true,
  60586. configurable: true
  60587. });
  60588. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60589. get: function () {
  60590. return this._volumetricLightStepsCount;
  60591. },
  60592. set: function (count) {
  60593. if (this.volumetricLightPostProcess) {
  60594. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60595. }
  60596. this._volumetricLightStepsCount = count;
  60597. },
  60598. enumerable: true,
  60599. configurable: true
  60600. });
  60601. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60602. get: function () {
  60603. return this._motionBlurSamples;
  60604. },
  60605. set: function (samples) {
  60606. if (this.motionBlurPostProcess) {
  60607. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60608. }
  60609. this._motionBlurSamples = samples;
  60610. },
  60611. enumerable: true,
  60612. configurable: true
  60613. });
  60614. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60615. var _this = this;
  60616. var ratio = this._ratio;
  60617. var scene = this._scene;
  60618. this._disposePostProcesses();
  60619. this._reset();
  60620. // Create pass post-process
  60621. if (!this._basePostProcess) {
  60622. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60623. this.originalPostProcess.onApply = function (effect) {
  60624. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60625. };
  60626. }
  60627. else {
  60628. this.originalPostProcess = this._basePostProcess;
  60629. }
  60630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60631. this._currentDepthOfFieldSource = this.originalPostProcess;
  60632. if (this._vlsEnabled) {
  60633. // Create volumetric light
  60634. this._createVolumetricLightPostProcess(scene, ratio);
  60635. // Create volumetric light final post-process
  60636. 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);
  60637. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60638. }
  60639. if (this._bloomEnabled) {
  60640. // Create down sample X4 post-process
  60641. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60642. // Create bright pass post-process
  60643. this._createBrightPassPostProcess(scene, ratio / 2);
  60644. // Create gaussian blur post-processes (down sampling blurs)
  60645. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60646. // Create texture adder post-process
  60647. this._createTextureAdderPostProcess(scene, ratio);
  60648. // Create depth-of-field source post-process
  60649. 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);
  60650. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60651. }
  60652. if (this._lensFlareEnabled) {
  60653. // Create lens flare post-process
  60654. this._createLensFlarePostProcess(scene, ratio);
  60655. // Create depth-of-field source post-process post lens-flare and disable it now
  60656. 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);
  60657. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60658. }
  60659. if (this._hdrEnabled) {
  60660. // Create luminance
  60661. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60662. // Create HDR
  60663. this._createHdrPostProcess(scene, ratio);
  60664. // Create depth-of-field source post-process post hdr and disable it now
  60665. 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);
  60666. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60667. }
  60668. if (this._depthOfFieldEnabled) {
  60669. // Create gaussian blur used by depth-of-field
  60670. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60671. // Create depth-of-field post-process
  60672. this._createDepthOfFieldPostProcess(scene, ratio);
  60673. }
  60674. if (this._motionBlurEnabled) {
  60675. // Create motion blur post-process
  60676. this._createMotionBlurPostProcess(scene, ratio);
  60677. }
  60678. if (this._cameras !== null) {
  60679. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60680. }
  60681. };
  60682. // Down Sample X4 Post-Processs
  60683. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60684. var _this = this;
  60685. var downSampleX4Offsets = new Array(32);
  60686. 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);
  60687. this.downSampleX4PostProcess.onApply = function (effect) {
  60688. var id = 0;
  60689. var width = _this.downSampleX4PostProcess.width;
  60690. var height = _this.downSampleX4PostProcess.height;
  60691. for (var i = -2; i < 2; i++) {
  60692. for (var j = -2; j < 2; j++) {
  60693. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60694. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  60695. id += 2;
  60696. }
  60697. }
  60698. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60699. };
  60700. // Add to pipeline
  60701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60702. };
  60703. // Brightpass Post-Process
  60704. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60705. var _this = this;
  60706. var brightOffsets = new Array(8);
  60707. 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);
  60708. this.brightPassPostProcess.onApply = function (effect) {
  60709. var sU = (1.0 / _this.brightPassPostProcess.width);
  60710. var sV = (1.0 / _this.brightPassPostProcess.height);
  60711. brightOffsets[0] = -0.5 * sU;
  60712. brightOffsets[1] = 0.5 * sV;
  60713. brightOffsets[2] = 0.5 * sU;
  60714. brightOffsets[3] = 0.5 * sV;
  60715. brightOffsets[4] = -0.5 * sU;
  60716. brightOffsets[5] = -0.5 * sV;
  60717. brightOffsets[6] = 0.5 * sU;
  60718. brightOffsets[7] = -0.5 * sV;
  60719. effect.setArray2("dsOffsets", brightOffsets);
  60720. effect.setFloat("brightThreshold", _this.brightThreshold);
  60721. };
  60722. // Add to pipeline
  60723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60724. };
  60725. // Create blur H&V post-processes
  60726. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  60727. var _this = this;
  60728. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  60729. var engine = scene.getEngine();
  60730. 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);
  60731. 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);
  60732. blurX.onActivateObservable.add(function () {
  60733. var dw = blurX.width / engine.getRenderWidth();
  60734. blurX.kernel = _this[blurWidthKey] * dw;
  60735. });
  60736. blurY.onActivateObservable.add(function () {
  60737. var dw = blurY.height / engine.getRenderHeight();
  60738. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  60739. });
  60740. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  60741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  60742. this.blurHPostProcesses.push(blurX);
  60743. this.blurVPostProcesses.push(blurY);
  60744. };
  60745. // Create texture adder post-process
  60746. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  60747. var _this = this;
  60748. 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);
  60749. this.textureAdderPostProcess.onApply = function (effect) {
  60750. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  60751. effect.setTexture("lensSampler", _this.lensTexture);
  60752. effect.setFloat("exposure", _this.exposure);
  60753. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  60754. };
  60755. // Add to pipeline
  60756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  60757. };
  60758. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  60759. var _this = this;
  60760. var geometryRenderer = scene.enableGeometryBufferRenderer();
  60761. geometryRenderer.enablePosition = true;
  60762. var geometry = geometryRenderer.getGBuffer();
  60763. // Base post-process
  60764. 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));
  60765. var depthValues = BABYLON.Vector2.Zero();
  60766. this.volumetricLightPostProcess.onApply = function (effect) {
  60767. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  60768. var generator = _this.sourceLight.getShadowGenerator();
  60769. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  60770. effect.setTexture("positionSampler", geometry.textures[2]);
  60771. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  60772. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  60773. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  60774. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  60775. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  60776. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  60777. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  60778. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  60779. effect.setVector2("depthValues", depthValues);
  60780. }
  60781. };
  60782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  60783. // Smooth
  60784. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  60785. // Merge
  60786. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  60787. this.volumetricLightMergePostProces.onApply = function (effect) {
  60788. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  60789. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  60790. };
  60791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  60792. };
  60793. // Create luminance
  60794. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  60795. var _this = this;
  60796. // Create luminance
  60797. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  60798. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  60799. var offsets = [];
  60800. this.luminancePostProcess.onApply = function (effect) {
  60801. var sU = (1.0 / _this.luminancePostProcess.width);
  60802. var sV = (1.0 / _this.luminancePostProcess.height);
  60803. offsets[0] = -0.5 * sU;
  60804. offsets[1] = 0.5 * sV;
  60805. offsets[2] = 0.5 * sU;
  60806. offsets[3] = 0.5 * sV;
  60807. offsets[4] = -0.5 * sU;
  60808. offsets[5] = -0.5 * sV;
  60809. offsets[6] = 0.5 * sU;
  60810. offsets[7] = -0.5 * sV;
  60811. effect.setArray2("lumOffsets", offsets);
  60812. };
  60813. // Add to pipeline
  60814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  60815. // Create down sample luminance
  60816. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  60817. var size = Math.pow(3, i);
  60818. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  60819. if (i === 0) {
  60820. defines += "#define FINAL_DOWN_SAMPLER";
  60821. }
  60822. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  60823. this.luminanceDownSamplePostProcesses.push(postProcess);
  60824. }
  60825. // Create callbacks and add effects
  60826. var lastLuminance = this.luminancePostProcess;
  60827. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  60828. var downSampleOffsets = new Array(18);
  60829. pp.onApply = function (effect) {
  60830. if (!lastLuminance) {
  60831. return;
  60832. }
  60833. var id = 0;
  60834. for (var x = -1; x < 2; x++) {
  60835. for (var y = -1; y < 2; y++) {
  60836. downSampleOffsets[id] = x / lastLuminance.width;
  60837. downSampleOffsets[id + 1] = y / lastLuminance.height;
  60838. id += 2;
  60839. }
  60840. }
  60841. effect.setArray2("dsOffsets", downSampleOffsets);
  60842. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  60843. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60844. lastLuminance = _this.luminancePostProcess;
  60845. }
  60846. else {
  60847. lastLuminance = pp;
  60848. }
  60849. };
  60850. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60851. pp.onAfterRender = function (effect) {
  60852. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  60853. 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);
  60854. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  60855. };
  60856. }
  60857. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  60858. });
  60859. };
  60860. // Create HDR post-process
  60861. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  60862. var _this = this;
  60863. 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);
  60864. var outputLiminance = 1;
  60865. var time = 0;
  60866. var lastTime = 0;
  60867. this.hdrPostProcess.onApply = function (effect) {
  60868. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  60869. time += scene.getEngine().getDeltaTime();
  60870. if (outputLiminance < 0) {
  60871. outputLiminance = _this._hdrCurrentLuminance;
  60872. }
  60873. else {
  60874. var dt = (lastTime - time) / 1000.0;
  60875. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  60876. outputLiminance += _this.hdrDecreaseRate * dt;
  60877. }
  60878. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  60879. outputLiminance -= _this.hdrIncreaseRate * dt;
  60880. }
  60881. else {
  60882. outputLiminance = _this._hdrCurrentLuminance;
  60883. }
  60884. }
  60885. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  60886. effect.setFloat("averageLuminance", outputLiminance);
  60887. lastTime = time;
  60888. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  60889. };
  60890. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  60891. };
  60892. // Create lens flare post-process
  60893. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  60894. var _this = this;
  60895. 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);
  60896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  60897. this._createBlurPostProcesses(scene, ratio / 4, 2);
  60898. 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);
  60899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  60900. var resolution = new BABYLON.Vector2(0, 0);
  60901. // Lens flare
  60902. this.lensFlarePostProcess.onApply = function (effect) {
  60903. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  60904. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60905. effect.setFloat("strength", _this.lensFlareStrength);
  60906. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60907. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60908. // Shift
  60909. resolution.x = _this.lensFlarePostProcess.width;
  60910. resolution.y = _this.lensFlarePostProcess.height;
  60911. effect.setVector2("resolution", resolution);
  60912. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60913. };
  60914. // Compose
  60915. 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);
  60916. 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);
  60917. this.lensFlareComposePostProcess.onApply = function (effect) {
  60918. if (!_this._scene.activeCamera) {
  60919. return;
  60920. }
  60921. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60922. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60923. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60924. // Lens start rotation matrix
  60925. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60926. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60927. 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));
  60928. camRot *= 4.0;
  60929. 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);
  60930. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60931. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60932. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  60933. };
  60934. };
  60935. // Create depth-of-field post-process
  60936. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60937. var _this = this;
  60938. 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);
  60939. this.depthOfFieldPostProcess.onApply = function (effect) {
  60940. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60941. effect.setTexture("depthSampler", _this._getDepthTexture());
  60942. effect.setFloat("distance", _this.depthOfFieldDistance);
  60943. };
  60944. // Add to pipeline
  60945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60946. };
  60947. // Create motion blur post-process
  60948. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  60949. var _this = this;
  60950. 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);
  60951. var motionScale = 0;
  60952. var prevViewProjection = BABYLON.Matrix.Identity();
  60953. var invViewProjection = BABYLON.Matrix.Identity();
  60954. var viewProjection = BABYLON.Matrix.Identity();
  60955. var screenSize = BABYLON.Vector2.Zero();
  60956. this.motionBlurPostProcess.onApply = function (effect) {
  60957. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  60958. viewProjection.invertToRef(invViewProjection);
  60959. effect.setMatrix("inverseViewProjection", invViewProjection);
  60960. effect.setMatrix("prevViewProjection", prevViewProjection);
  60961. prevViewProjection = viewProjection;
  60962. screenSize.x = _this.motionBlurPostProcess.width;
  60963. screenSize.y = _this.motionBlurPostProcess.height;
  60964. effect.setVector2("screenSize", screenSize);
  60965. motionScale = scene.getEngine().getFps() / 60.0;
  60966. effect.setFloat("motionScale", motionScale);
  60967. effect.setFloat("motionStrength", _this.motionStrength);
  60968. effect.setTexture("depthSampler", _this._getDepthTexture());
  60969. };
  60970. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  60971. };
  60972. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  60973. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  60974. var renderer = this._scene.enableGeometryBufferRenderer();
  60975. return renderer.getGBuffer().textures[0];
  60976. }
  60977. return this._scene.enableDepthRenderer().getDepthMap();
  60978. };
  60979. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  60980. for (var i = 0; i < this._cameras.length; i++) {
  60981. var camera = this._cameras[i];
  60982. if (this.originalPostProcess) {
  60983. this.originalPostProcess.dispose(camera);
  60984. }
  60985. if (this.downSampleX4PostProcess) {
  60986. this.downSampleX4PostProcess.dispose(camera);
  60987. }
  60988. if (this.brightPassPostProcess) {
  60989. this.brightPassPostProcess.dispose(camera);
  60990. }
  60991. if (this.textureAdderPostProcess) {
  60992. this.textureAdderPostProcess.dispose(camera);
  60993. }
  60994. if (this.textureAdderFinalPostProcess) {
  60995. this.textureAdderFinalPostProcess.dispose(camera);
  60996. }
  60997. if (this.volumetricLightPostProcess) {
  60998. this.volumetricLightPostProcess.dispose(camera);
  60999. }
  61000. if (this.volumetricLightSmoothXPostProcess) {
  61001. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61002. }
  61003. if (this.volumetricLightSmoothYPostProcess) {
  61004. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61005. }
  61006. if (this.volumetricLightMergePostProces) {
  61007. this.volumetricLightMergePostProces.dispose(camera);
  61008. }
  61009. if (this.volumetricLightFinalPostProcess) {
  61010. this.volumetricLightFinalPostProcess.dispose(camera);
  61011. }
  61012. if (this.lensFlarePostProcess) {
  61013. this.lensFlarePostProcess.dispose(camera);
  61014. }
  61015. if (this.lensFlareComposePostProcess) {
  61016. this.lensFlareComposePostProcess.dispose(camera);
  61017. }
  61018. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61019. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61020. }
  61021. if (this.luminancePostProcess) {
  61022. this.luminancePostProcess.dispose(camera);
  61023. }
  61024. if (this.hdrPostProcess) {
  61025. this.hdrPostProcess.dispose(camera);
  61026. }
  61027. if (this.hdrFinalPostProcess) {
  61028. this.hdrFinalPostProcess.dispose(camera);
  61029. }
  61030. if (this.depthOfFieldPostProcess) {
  61031. this.depthOfFieldPostProcess.dispose(camera);
  61032. }
  61033. if (this.motionBlurPostProcess) {
  61034. this.motionBlurPostProcess.dispose(camera);
  61035. }
  61036. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61037. this.blurHPostProcesses[j].dispose(camera);
  61038. }
  61039. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61040. this.blurVPostProcesses[j].dispose(camera);
  61041. }
  61042. }
  61043. this.originalPostProcess = null;
  61044. this.downSampleX4PostProcess = null;
  61045. this.brightPassPostProcess = null;
  61046. this.textureAdderPostProcess = null;
  61047. this.textureAdderFinalPostProcess = null;
  61048. this.volumetricLightPostProcess = null;
  61049. this.volumetricLightSmoothXPostProcess = null;
  61050. this.volumetricLightSmoothYPostProcess = null;
  61051. this.volumetricLightMergePostProces = null;
  61052. this.volumetricLightFinalPostProcess = null;
  61053. this.lensFlarePostProcess = null;
  61054. this.lensFlareComposePostProcess = null;
  61055. this.luminancePostProcess = null;
  61056. this.hdrPostProcess = null;
  61057. this.hdrFinalPostProcess = null;
  61058. this.depthOfFieldPostProcess = null;
  61059. this.motionBlurPostProcess = null;
  61060. this.luminanceDownSamplePostProcesses = [];
  61061. this.blurHPostProcesses = [];
  61062. this.blurVPostProcesses = [];
  61063. };
  61064. // Dispose
  61065. StandardRenderingPipeline.prototype.dispose = function () {
  61066. this._disposePostProcesses();
  61067. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61068. _super.prototype.dispose.call(this);
  61069. };
  61070. // Serialize rendering pipeline
  61071. StandardRenderingPipeline.prototype.serialize = function () {
  61072. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61073. serializationObject.customType = "StandardRenderingPipeline";
  61074. return serializationObject;
  61075. };
  61076. /**
  61077. * Static members
  61078. */
  61079. // Parse serialized pipeline
  61080. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61081. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61082. };
  61083. // Luminance steps
  61084. StandardRenderingPipeline.LuminanceSteps = 6;
  61085. __decorate([
  61086. BABYLON.serialize()
  61087. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61088. __decorate([
  61089. BABYLON.serialize()
  61090. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61091. __decorate([
  61092. BABYLON.serialize()
  61093. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61094. __decorate([
  61095. BABYLON.serialize()
  61096. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61097. __decorate([
  61098. BABYLON.serializeAsTexture("lensTexture")
  61099. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61100. __decorate([
  61101. BABYLON.serialize()
  61102. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61103. __decorate([
  61104. BABYLON.serialize()
  61105. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61106. __decorate([
  61107. BABYLON.serialize()
  61108. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61109. __decorate([
  61110. BABYLON.serialize()
  61111. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61112. __decorate([
  61113. BABYLON.serialize()
  61114. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61115. __decorate([
  61116. BABYLON.serialize()
  61117. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61118. __decorate([
  61119. BABYLON.serializeAsTexture("lensColorTexture")
  61120. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61121. __decorate([
  61122. BABYLON.serialize()
  61123. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61124. __decorate([
  61125. BABYLON.serialize()
  61126. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61127. __decorate([
  61128. BABYLON.serialize()
  61129. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61130. __decorate([
  61131. BABYLON.serialize()
  61132. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61133. __decorate([
  61134. BABYLON.serializeAsTexture("lensStarTexture")
  61135. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61136. __decorate([
  61137. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61138. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61139. __decorate([
  61140. BABYLON.serialize()
  61141. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61142. __decorate([
  61143. BABYLON.serialize()
  61144. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61145. __decorate([
  61146. BABYLON.serialize()
  61147. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61148. __decorate([
  61149. BABYLON.serialize()
  61150. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61151. __decorate([
  61152. BABYLON.serialize()
  61153. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61154. __decorate([
  61155. BABYLON.serialize()
  61156. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61157. __decorate([
  61158. BABYLON.serialize()
  61159. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61160. __decorate([
  61161. BABYLON.serialize()
  61162. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61163. __decorate([
  61164. BABYLON.serialize()
  61165. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61166. __decorate([
  61167. BABYLON.serialize()
  61168. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61169. __decorate([
  61170. BABYLON.serialize()
  61171. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61172. __decorate([
  61173. BABYLON.serialize()
  61174. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61175. return StandardRenderingPipeline;
  61176. }(BABYLON.PostProcessRenderPipeline));
  61177. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61178. })(BABYLON || (BABYLON = {}));
  61179. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61180. var BABYLON;
  61181. (function (BABYLON) {
  61182. var FxaaPostProcess = /** @class */ (function (_super) {
  61183. __extends(FxaaPostProcess, _super);
  61184. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61185. if (camera === void 0) { camera = null; }
  61186. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61187. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61188. _this.onApplyObservable.add(function (effect) {
  61189. var texelSize = _this.texelSize;
  61190. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61191. });
  61192. return _this;
  61193. }
  61194. return FxaaPostProcess;
  61195. }(BABYLON.PostProcess));
  61196. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61197. })(BABYLON || (BABYLON = {}));
  61198. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61199. var BABYLON;
  61200. (function (BABYLON) {
  61201. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61202. __extends(DefaultRenderingPipeline, _super);
  61203. /**
  61204. * @constructor
  61205. * @param {string} name - The rendering pipeline name
  61206. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61207. * @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)
  61208. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61209. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61210. */
  61211. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61212. if (automaticBuild === void 0) { automaticBuild = true; }
  61213. var _this = _super.call(this, scene.getEngine(), name) || this;
  61214. _this.PassPostProcessId = "PassPostProcessEffect";
  61215. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61216. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61217. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61218. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61219. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61220. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61221. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61222. // IAnimatable
  61223. _this.animations = [];
  61224. // Values
  61225. _this._bloomEnabled = false;
  61226. _this._fxaaEnabled = false;
  61227. _this._imageProcessingEnabled = true;
  61228. _this._bloomScale = 0.6;
  61229. _this._buildAllowed = true;
  61230. /**
  61231. * Specifies the size of the bloom blur kernel, relative to the final output size
  61232. */
  61233. _this.bloomKernel = 64;
  61234. /**
  61235. * Specifies the weight of the bloom in the final rendering
  61236. */
  61237. _this._bloomWeight = 0.15;
  61238. _this._cameras = cameras || [];
  61239. _this._buildAllowed = automaticBuild;
  61240. // Initialize
  61241. _this._scene = scene;
  61242. var caps = _this._scene.getEngine().getCaps();
  61243. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61244. // Misc
  61245. if (_this._hdr) {
  61246. if (caps.textureHalfFloatRender) {
  61247. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61248. }
  61249. else if (caps.textureFloatRender) {
  61250. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61251. }
  61252. }
  61253. else {
  61254. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61255. }
  61256. // Attach
  61257. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61258. _this._buildPipeline();
  61259. return _this;
  61260. }
  61261. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61262. get: function () {
  61263. return this._bloomWeight;
  61264. },
  61265. set: function (value) {
  61266. if (this._bloomWeight === value) {
  61267. return;
  61268. }
  61269. this._bloomWeight = value;
  61270. if (this._hdr && this.copyBack) {
  61271. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61272. }
  61273. },
  61274. enumerable: true,
  61275. configurable: true
  61276. });
  61277. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61278. get: function () {
  61279. return this._bloomScale;
  61280. },
  61281. set: function (value) {
  61282. if (this._bloomScale === value) {
  61283. return;
  61284. }
  61285. this._bloomScale = value;
  61286. this._buildPipeline();
  61287. },
  61288. enumerable: true,
  61289. configurable: true
  61290. });
  61291. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61292. get: function () {
  61293. return this._bloomEnabled;
  61294. },
  61295. set: function (enabled) {
  61296. if (this._bloomEnabled === enabled) {
  61297. return;
  61298. }
  61299. this._bloomEnabled = enabled;
  61300. this._buildPipeline();
  61301. },
  61302. enumerable: true,
  61303. configurable: true
  61304. });
  61305. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61306. get: function () {
  61307. return this._fxaaEnabled;
  61308. },
  61309. set: function (enabled) {
  61310. if (this._fxaaEnabled === enabled) {
  61311. return;
  61312. }
  61313. this._fxaaEnabled = enabled;
  61314. this._buildPipeline();
  61315. },
  61316. enumerable: true,
  61317. configurable: true
  61318. });
  61319. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61320. get: function () {
  61321. return this._imageProcessingEnabled;
  61322. },
  61323. set: function (enabled) {
  61324. if (this._imageProcessingEnabled === enabled) {
  61325. return;
  61326. }
  61327. this._imageProcessingEnabled = enabled;
  61328. this._buildPipeline();
  61329. },
  61330. enumerable: true,
  61331. configurable: true
  61332. });
  61333. /**
  61334. * Force the compilation of the entire pipeline.
  61335. */
  61336. DefaultRenderingPipeline.prototype.prepare = function () {
  61337. var previousState = this._buildAllowed;
  61338. this._buildAllowed = true;
  61339. this._buildPipeline();
  61340. this._buildAllowed = previousState;
  61341. };
  61342. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61343. var _this = this;
  61344. if (!this._buildAllowed) {
  61345. return;
  61346. }
  61347. var engine = this._scene.getEngine();
  61348. this._disposePostProcesses();
  61349. this._reset();
  61350. if (this.bloomEnabled) {
  61351. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61352. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61353. if (!this._hdr) {
  61354. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61355. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61356. this.highlights.autoClear = false;
  61357. this.highlights.alwaysForcePOT = true;
  61358. }
  61359. 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);
  61360. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61361. this.blurX.alwaysForcePOT = true;
  61362. this.blurX.autoClear = false;
  61363. this.blurX.onActivateObservable.add(function () {
  61364. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61365. _this.blurX.kernel = _this.bloomKernel * dw;
  61366. });
  61367. 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);
  61368. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61369. this.blurY.alwaysForcePOT = true;
  61370. this.blurY.autoClear = false;
  61371. this.blurY.onActivateObservable.add(function () {
  61372. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61373. _this.blurY.kernel = _this.bloomKernel * dh;
  61374. });
  61375. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61376. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61377. this.copyBack.alwaysForcePOT = true;
  61378. if (this._hdr) {
  61379. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61380. var w = this.bloomWeight;
  61381. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61382. }
  61383. else {
  61384. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61385. }
  61386. this.copyBack.autoClear = false;
  61387. }
  61388. if (this._imageProcessingEnabled) {
  61389. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61390. if (this._hdr) {
  61391. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61392. }
  61393. else {
  61394. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61395. }
  61396. }
  61397. if (this.fxaaEnabled) {
  61398. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61399. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61400. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61401. }
  61402. else if (this._hdr && this.imageProcessing) {
  61403. this.finalMerge = this.imageProcessing;
  61404. }
  61405. else {
  61406. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61407. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61408. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61409. }
  61410. if (this.bloomEnabled) {
  61411. if (this._hdr) {
  61412. this.copyBack.shareOutputWith(this.blurX);
  61413. if (this.imageProcessing) {
  61414. this.imageProcessing.shareOutputWith(this.pass);
  61415. this.imageProcessing.autoClear = false;
  61416. }
  61417. else if (this.fxaa) {
  61418. this.fxaa.shareOutputWith(this.pass);
  61419. }
  61420. else {
  61421. this.finalMerge.shareOutputWith(this.pass);
  61422. }
  61423. }
  61424. else {
  61425. if (this.fxaa) {
  61426. this.fxaa.shareOutputWith(this.pass);
  61427. }
  61428. else {
  61429. this.finalMerge.shareOutputWith(this.pass);
  61430. }
  61431. }
  61432. }
  61433. if (this._cameras !== null) {
  61434. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61435. }
  61436. };
  61437. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61438. for (var i = 0; i < this._cameras.length; i++) {
  61439. var camera = this._cameras[i];
  61440. if (this.pass) {
  61441. this.pass.dispose(camera);
  61442. }
  61443. if (this.highlights) {
  61444. this.highlights.dispose(camera);
  61445. }
  61446. if (this.blurX) {
  61447. this.blurX.dispose(camera);
  61448. }
  61449. if (this.blurY) {
  61450. this.blurY.dispose(camera);
  61451. }
  61452. if (this.copyBack) {
  61453. this.copyBack.dispose(camera);
  61454. }
  61455. if (this.imageProcessing) {
  61456. this.imageProcessing.dispose(camera);
  61457. }
  61458. if (this.fxaa) {
  61459. this.fxaa.dispose(camera);
  61460. }
  61461. if (this.finalMerge) {
  61462. this.finalMerge.dispose(camera);
  61463. }
  61464. }
  61465. this.pass = null;
  61466. this.highlights = null;
  61467. this.blurX = null;
  61468. this.blurY = null;
  61469. this.copyBack = null;
  61470. this.imageProcessing = null;
  61471. this.fxaa = null;
  61472. this.finalMerge = null;
  61473. };
  61474. // Dispose
  61475. DefaultRenderingPipeline.prototype.dispose = function () {
  61476. this._disposePostProcesses();
  61477. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61478. _super.prototype.dispose.call(this);
  61479. };
  61480. // Serialize rendering pipeline
  61481. DefaultRenderingPipeline.prototype.serialize = function () {
  61482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61483. serializationObject.customType = "DefaultRenderingPipeline";
  61484. return serializationObject;
  61485. };
  61486. // Parse serialized pipeline
  61487. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61488. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61489. };
  61490. __decorate([
  61491. BABYLON.serialize()
  61492. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61493. __decorate([
  61494. BABYLON.serialize()
  61495. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61496. __decorate([
  61497. BABYLON.serialize()
  61498. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61499. __decorate([
  61500. BABYLON.serialize()
  61501. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61502. __decorate([
  61503. BABYLON.serialize()
  61504. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61505. __decorate([
  61506. BABYLON.serialize()
  61507. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61508. __decorate([
  61509. BABYLON.serialize()
  61510. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61511. __decorate([
  61512. BABYLON.serialize()
  61513. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61514. return DefaultRenderingPipeline;
  61515. }(BABYLON.PostProcessRenderPipeline));
  61516. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61517. })(BABYLON || (BABYLON = {}));
  61518. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61519. var BABYLON;
  61520. (function (BABYLON) {
  61521. var GeometryBufferRenderer = /** @class */ (function () {
  61522. function GeometryBufferRenderer(scene, ratio) {
  61523. if (ratio === void 0) { ratio = 1; }
  61524. this._enablePosition = false;
  61525. this._scene = scene;
  61526. this._ratio = ratio;
  61527. // Render target
  61528. this._createRenderTargets();
  61529. }
  61530. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61531. set: function (meshes) {
  61532. this._multiRenderTarget.renderList = meshes;
  61533. },
  61534. enumerable: true,
  61535. configurable: true
  61536. });
  61537. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61538. get: function () {
  61539. return this._multiRenderTarget.isSupported;
  61540. },
  61541. enumerable: true,
  61542. configurable: true
  61543. });
  61544. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61545. get: function () {
  61546. return this._enablePosition;
  61547. },
  61548. set: function (enable) {
  61549. this._enablePosition = enable;
  61550. this.dispose();
  61551. this._createRenderTargets();
  61552. },
  61553. enumerable: true,
  61554. configurable: true
  61555. });
  61556. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61557. var material = subMesh.getMaterial();
  61558. if (material && material.disableDepthWrite) {
  61559. return false;
  61560. }
  61561. var defines = [];
  61562. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61563. var mesh = subMesh.getMesh();
  61564. // Alpha test
  61565. if (material && material.needAlphaTesting()) {
  61566. defines.push("#define ALPHATEST");
  61567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61568. attribs.push(BABYLON.VertexBuffer.UVKind);
  61569. defines.push("#define UV1");
  61570. }
  61571. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61572. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61573. defines.push("#define UV2");
  61574. }
  61575. }
  61576. // Buffers
  61577. if (this._enablePosition) {
  61578. defines.push("#define POSITION");
  61579. }
  61580. // Bones
  61581. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61582. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61583. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61584. if (mesh.numBoneInfluencers > 4) {
  61585. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61586. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61587. }
  61588. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61589. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61590. }
  61591. else {
  61592. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61593. }
  61594. // Instances
  61595. if (useInstances) {
  61596. defines.push("#define INSTANCES");
  61597. attribs.push("world0");
  61598. attribs.push("world1");
  61599. attribs.push("world2");
  61600. attribs.push("world3");
  61601. }
  61602. // Get correct effect
  61603. var join = defines.join("\n");
  61604. if (this._cachedDefines !== join) {
  61605. this._cachedDefines = join;
  61606. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61607. }
  61608. return this._effect.isReady();
  61609. };
  61610. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61611. return this._multiRenderTarget;
  61612. };
  61613. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61614. get: function () {
  61615. return this._multiRenderTarget.samples;
  61616. },
  61617. set: function (value) {
  61618. this._multiRenderTarget.samples = value;
  61619. },
  61620. enumerable: true,
  61621. configurable: true
  61622. });
  61623. // Methods
  61624. GeometryBufferRenderer.prototype.dispose = function () {
  61625. this.getGBuffer().dispose();
  61626. };
  61627. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61628. var _this = this;
  61629. var engine = this._scene.getEngine();
  61630. var count = this._enablePosition ? 3 : 2;
  61631. 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 });
  61632. if (!this.isSupported) {
  61633. return;
  61634. }
  61635. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61636. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61637. this._multiRenderTarget.refreshRate = 1;
  61638. this._multiRenderTarget.renderParticles = false;
  61639. this._multiRenderTarget.renderList = null;
  61640. // set default depth value to 1.0 (far away)
  61641. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61642. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61643. });
  61644. // Custom render function
  61645. var renderSubMesh = function (subMesh) {
  61646. var mesh = subMesh.getRenderingMesh();
  61647. var scene = _this._scene;
  61648. var engine = scene.getEngine();
  61649. var material = subMesh.getMaterial();
  61650. if (!material) {
  61651. return;
  61652. }
  61653. // Culling
  61654. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61655. // Managing instances
  61656. var batch = mesh._getInstancesRenderList(subMesh._id);
  61657. if (batch.mustReturn) {
  61658. return;
  61659. }
  61660. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61661. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61662. engine.enableEffect(_this._effect);
  61663. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61664. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61665. _this._effect.setMatrix("view", scene.getViewMatrix());
  61666. // Alpha test
  61667. if (material && material.needAlphaTesting()) {
  61668. var alphaTexture = material.getAlphaTestTexture();
  61669. if (alphaTexture) {
  61670. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61671. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61672. }
  61673. }
  61674. // Bones
  61675. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61676. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61677. }
  61678. // Draw
  61679. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61680. }
  61681. };
  61682. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61683. var index;
  61684. if (depthOnlySubMeshes.length) {
  61685. engine.setColorWrite(false);
  61686. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61687. renderSubMesh(depthOnlySubMeshes.data[index]);
  61688. }
  61689. engine.setColorWrite(true);
  61690. }
  61691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61692. renderSubMesh(opaqueSubMeshes.data[index]);
  61693. }
  61694. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61695. renderSubMesh(alphaTestSubMeshes.data[index]);
  61696. }
  61697. };
  61698. };
  61699. return GeometryBufferRenderer;
  61700. }());
  61701. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  61702. })(BABYLON || (BABYLON = {}));
  61703. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  61704. var BABYLON;
  61705. (function (BABYLON) {
  61706. var RefractionPostProcess = /** @class */ (function (_super) {
  61707. __extends(RefractionPostProcess, _super);
  61708. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  61709. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  61710. _this.color = color;
  61711. _this.depth = depth;
  61712. _this.colorLevel = colorLevel;
  61713. _this.onActivateObservable.add(function (cam) {
  61714. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  61715. });
  61716. _this.onApplyObservable.add(function (effect) {
  61717. effect.setColor3("baseColor", _this.color);
  61718. effect.setFloat("depth", _this.depth);
  61719. effect.setFloat("colorLevel", _this.colorLevel);
  61720. effect.setTexture("refractionSampler", _this._refRexture);
  61721. });
  61722. return _this;
  61723. }
  61724. // Methods
  61725. RefractionPostProcess.prototype.dispose = function (camera) {
  61726. if (this._refRexture) {
  61727. this._refRexture.dispose();
  61728. }
  61729. _super.prototype.dispose.call(this, camera);
  61730. };
  61731. return RefractionPostProcess;
  61732. }(BABYLON.PostProcess));
  61733. BABYLON.RefractionPostProcess = RefractionPostProcess;
  61734. })(BABYLON || (BABYLON = {}));
  61735. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  61736. var BABYLON;
  61737. (function (BABYLON) {
  61738. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  61739. __extends(BlackAndWhitePostProcess, _super);
  61740. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  61741. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  61742. _this.degree = 1;
  61743. _this.onApplyObservable.add(function (effect) {
  61744. effect.setFloat("degree", _this.degree);
  61745. });
  61746. return _this;
  61747. }
  61748. return BlackAndWhitePostProcess;
  61749. }(BABYLON.PostProcess));
  61750. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  61751. })(BABYLON || (BABYLON = {}));
  61752. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  61753. var BABYLON;
  61754. (function (BABYLON) {
  61755. var ConvolutionPostProcess = /** @class */ (function (_super) {
  61756. __extends(ConvolutionPostProcess, _super);
  61757. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  61758. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  61759. _this.kernel = kernel;
  61760. _this.onApply = function (effect) {
  61761. effect.setFloat2("screenSize", _this.width, _this.height);
  61762. effect.setArray("kernel", _this.kernel);
  61763. };
  61764. return _this;
  61765. }
  61766. // Statics
  61767. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  61768. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  61769. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  61770. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  61771. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  61772. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  61773. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  61774. return ConvolutionPostProcess;
  61775. }(BABYLON.PostProcess));
  61776. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  61777. })(BABYLON || (BABYLON = {}));
  61778. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  61779. var BABYLON;
  61780. (function (BABYLON) {
  61781. var FilterPostProcess = /** @class */ (function (_super) {
  61782. __extends(FilterPostProcess, _super);
  61783. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  61784. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  61785. _this.kernelMatrix = kernelMatrix;
  61786. _this.onApply = function (effect) {
  61787. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  61788. };
  61789. return _this;
  61790. }
  61791. return FilterPostProcess;
  61792. }(BABYLON.PostProcess));
  61793. BABYLON.FilterPostProcess = FilterPostProcess;
  61794. })(BABYLON || (BABYLON = {}));
  61795. //# sourceMappingURL=babylon.filterPostProcess.js.map
  61796. var BABYLON;
  61797. (function (BABYLON) {
  61798. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  61799. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  61800. __extends(VolumetricLightScatteringPostProcess, _super);
  61801. /**
  61802. * @constructor
  61803. * @param {string} name - The post-process name
  61804. * @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)
  61805. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  61806. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  61807. * @param {number} samples - The post-process quality, default 100
  61808. * @param {number} samplingMode - The post-process filtering mode
  61809. * @param {BABYLON.Engine} engine - The babylon engine
  61810. * @param {boolean} reusable - If the post-process is reusable
  61811. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  61812. */
  61813. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  61814. if (samples === void 0) { samples = 100; }
  61815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61816. 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;
  61817. _this._screenCoordinates = BABYLON.Vector2.Zero();
  61818. /**
  61819. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  61820. * @type {Vector3}
  61821. */
  61822. _this.customMeshPosition = BABYLON.Vector3.Zero();
  61823. /**
  61824. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  61825. * @type {boolean}
  61826. */
  61827. _this.useCustomMeshPosition = false;
  61828. /**
  61829. * If the post-process should inverse the light scattering direction
  61830. * @type {boolean}
  61831. */
  61832. _this.invert = true;
  61833. /**
  61834. * Array containing the excluded meshes not rendered in the internal pass
  61835. */
  61836. _this.excludedMeshes = new Array();
  61837. /**
  61838. * Controls the overall intensity of the post-process
  61839. * @type {number}
  61840. */
  61841. _this.exposure = 0.3;
  61842. /**
  61843. * Dissipates each sample's contribution in range [0, 1]
  61844. * @type {number}
  61845. */
  61846. _this.decay = 0.96815;
  61847. /**
  61848. * Controls the overall intensity of each sample
  61849. * @type {number}
  61850. */
  61851. _this.weight = 0.58767;
  61852. /**
  61853. * Controls the density of each sample
  61854. * @type {number}
  61855. */
  61856. _this.density = 0.926;
  61857. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  61858. engine = scene.getEngine();
  61859. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  61860. // Configure mesh
  61861. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  61862. // Configure
  61863. _this._createPass(scene, ratio.passRatio || ratio);
  61864. _this.onActivate = function (camera) {
  61865. if (!_this.isSupported) {
  61866. _this.dispose(camera);
  61867. }
  61868. _this.onActivate = null;
  61869. };
  61870. _this.onApplyObservable.add(function (effect) {
  61871. _this._updateMeshScreenCoordinates(scene);
  61872. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  61873. effect.setFloat("exposure", _this.exposure);
  61874. effect.setFloat("decay", _this.decay);
  61875. effect.setFloat("weight", _this.weight);
  61876. effect.setFloat("density", _this.density);
  61877. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  61878. });
  61879. return _this;
  61880. }
  61881. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  61882. get: function () {
  61883. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61884. return false;
  61885. },
  61886. set: function (useDiffuseColor) {
  61887. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61888. },
  61889. enumerable: true,
  61890. configurable: true
  61891. });
  61892. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  61893. return "VolumetricLightScatteringPostProcess";
  61894. };
  61895. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  61896. var mesh = subMesh.getMesh();
  61897. // Render this.mesh as default
  61898. if (mesh === this.mesh && mesh.material) {
  61899. return mesh.material.isReady(mesh);
  61900. }
  61901. var defines = [];
  61902. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61903. var material = subMesh.getMaterial();
  61904. // Alpha test
  61905. if (material) {
  61906. if (material.needAlphaTesting()) {
  61907. defines.push("#define ALPHATEST");
  61908. }
  61909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61910. attribs.push(BABYLON.VertexBuffer.UVKind);
  61911. defines.push("#define UV1");
  61912. }
  61913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61914. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61915. defines.push("#define UV2");
  61916. }
  61917. }
  61918. // Bones
  61919. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61920. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61921. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61922. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61923. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  61924. }
  61925. else {
  61926. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61927. }
  61928. // Instances
  61929. if (useInstances) {
  61930. defines.push("#define INSTANCES");
  61931. attribs.push("world0");
  61932. attribs.push("world1");
  61933. attribs.push("world2");
  61934. attribs.push("world3");
  61935. }
  61936. // Get correct effect
  61937. var join = defines.join("\n");
  61938. if (this._cachedDefines !== join) {
  61939. this._cachedDefines = join;
  61940. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  61941. }
  61942. return this._volumetricLightScatteringPass.isReady();
  61943. };
  61944. /**
  61945. * Sets the new light position for light scattering effect
  61946. * @param {BABYLON.Vector3} The new custom light position
  61947. */
  61948. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  61949. this.customMeshPosition = position;
  61950. };
  61951. /**
  61952. * Returns the light position for light scattering effect
  61953. * @return {BABYLON.Vector3} The custom light position
  61954. */
  61955. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  61956. return this.customMeshPosition;
  61957. };
  61958. /**
  61959. * Disposes the internal assets and detaches the post-process from the camera
  61960. */
  61961. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  61962. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  61963. if (rttIndex !== -1) {
  61964. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  61965. }
  61966. this._volumetricLightScatteringRTT.dispose();
  61967. _super.prototype.dispose.call(this, camera);
  61968. };
  61969. /**
  61970. * Returns the render target texture used by the post-process
  61971. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  61972. */
  61973. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  61974. return this._volumetricLightScatteringRTT;
  61975. };
  61976. // Private methods
  61977. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  61978. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  61979. return true;
  61980. }
  61981. return false;
  61982. };
  61983. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  61984. var _this = this;
  61985. var engine = scene.getEngine();
  61986. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61987. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61988. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61989. this._volumetricLightScatteringRTT.renderList = null;
  61990. this._volumetricLightScatteringRTT.renderParticles = false;
  61991. var camera = this.getCamera();
  61992. if (camera) {
  61993. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61994. }
  61995. else {
  61996. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61997. }
  61998. // Custom render function for submeshes
  61999. var renderSubMesh = function (subMesh) {
  62000. var mesh = subMesh.getRenderingMesh();
  62001. if (_this._meshExcluded(mesh)) {
  62002. return;
  62003. }
  62004. var material = subMesh.getMaterial();
  62005. if (!material) {
  62006. return;
  62007. }
  62008. var scene = mesh.getScene();
  62009. var engine = scene.getEngine();
  62010. // Culling
  62011. engine.setState(material.backFaceCulling);
  62012. // Managing instances
  62013. var batch = mesh._getInstancesRenderList(subMesh._id);
  62014. if (batch.mustReturn) {
  62015. return;
  62016. }
  62017. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62018. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  62019. var effect = _this._volumetricLightScatteringPass;
  62020. if (mesh === _this.mesh) {
  62021. if (subMesh.effect) {
  62022. effect = subMesh.effect;
  62023. }
  62024. else {
  62025. effect = material.getEffect();
  62026. }
  62027. }
  62028. engine.enableEffect(effect);
  62029. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62030. if (mesh === _this.mesh) {
  62031. material.bind(mesh.getWorldMatrix(), mesh);
  62032. }
  62033. else {
  62034. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62035. // Alpha test
  62036. if (material && material.needAlphaTesting()) {
  62037. var alphaTexture = material.getAlphaTestTexture();
  62038. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62039. if (alphaTexture) {
  62040. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62041. }
  62042. }
  62043. // Bones
  62044. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62045. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62046. }
  62047. }
  62048. // Draw
  62049. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62050. }
  62051. };
  62052. // Render target texture callbacks
  62053. var savedSceneClearColor;
  62054. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62055. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62056. savedSceneClearColor = scene.clearColor;
  62057. scene.clearColor = sceneClearColor;
  62058. });
  62059. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62060. scene.clearColor = savedSceneClearColor;
  62061. });
  62062. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62063. var engine = scene.getEngine();
  62064. var index;
  62065. if (depthOnlySubMeshes.length) {
  62066. engine.setColorWrite(false);
  62067. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62068. renderSubMesh(depthOnlySubMeshes.data[index]);
  62069. }
  62070. engine.setColorWrite(true);
  62071. }
  62072. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62073. renderSubMesh(opaqueSubMeshes.data[index]);
  62074. }
  62075. engine.setAlphaTesting(true);
  62076. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62077. renderSubMesh(alphaTestSubMeshes.data[index]);
  62078. }
  62079. engine.setAlphaTesting(false);
  62080. if (transparentSubMeshes.length) {
  62081. // Sort sub meshes
  62082. for (index = 0; index < transparentSubMeshes.length; index++) {
  62083. var submesh = transparentSubMeshes.data[index];
  62084. var boundingInfo = submesh.getBoundingInfo();
  62085. if (boundingInfo && scene.activeCamera) {
  62086. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62087. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62088. }
  62089. }
  62090. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62091. sortedArray.sort(function (a, b) {
  62092. // Alpha index first
  62093. if (a._alphaIndex > b._alphaIndex) {
  62094. return 1;
  62095. }
  62096. if (a._alphaIndex < b._alphaIndex) {
  62097. return -1;
  62098. }
  62099. // Then distance to camera
  62100. if (a._distanceToCamera < b._distanceToCamera) {
  62101. return 1;
  62102. }
  62103. if (a._distanceToCamera > b._distanceToCamera) {
  62104. return -1;
  62105. }
  62106. return 0;
  62107. });
  62108. // Render sub meshes
  62109. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62110. for (index = 0; index < sortedArray.length; index++) {
  62111. renderSubMesh(sortedArray[index]);
  62112. }
  62113. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62114. }
  62115. };
  62116. };
  62117. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62118. var transform = scene.getTransformMatrix();
  62119. var meshPosition;
  62120. if (this.useCustomMeshPosition) {
  62121. meshPosition = this.customMeshPosition;
  62122. }
  62123. else if (this.attachedNode) {
  62124. meshPosition = this.attachedNode.position;
  62125. }
  62126. else {
  62127. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62128. }
  62129. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62130. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62131. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62132. if (this.invert)
  62133. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62134. };
  62135. // Static methods
  62136. /**
  62137. * Creates a default mesh for the Volumeric Light Scattering post-process
  62138. * @param {string} The mesh name
  62139. * @param {BABYLON.Scene} The scene where to create the mesh
  62140. * @return {BABYLON.Mesh} the default mesh
  62141. */
  62142. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62143. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62144. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62145. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62146. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62147. mesh.material = material;
  62148. return mesh;
  62149. };
  62150. __decorate([
  62151. BABYLON.serializeAsVector3()
  62152. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62153. __decorate([
  62154. BABYLON.serialize()
  62155. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62156. __decorate([
  62157. BABYLON.serialize()
  62158. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62159. __decorate([
  62160. BABYLON.serializeAsMeshReference()
  62161. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62162. __decorate([
  62163. BABYLON.serialize()
  62164. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62165. __decorate([
  62166. BABYLON.serialize()
  62167. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62168. __decorate([
  62169. BABYLON.serialize()
  62170. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62171. __decorate([
  62172. BABYLON.serialize()
  62173. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62174. __decorate([
  62175. BABYLON.serialize()
  62176. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62177. return VolumetricLightScatteringPostProcess;
  62178. }(BABYLON.PostProcess));
  62179. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62180. })(BABYLON || (BABYLON = {}));
  62181. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62182. //
  62183. // This post-process allows the modification of rendered colors by using
  62184. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62185. //
  62186. // The object needs to be provided an url to a texture containing the color
  62187. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62188. // Use an image editing software to tweak the LUT to match your needs.
  62189. //
  62190. // For an example of a color LUT, see here:
  62191. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62192. // For explanations on color grading, see here:
  62193. // http://udn.epicgames.com/Three/ColorGrading.html
  62194. //
  62195. var BABYLON;
  62196. (function (BABYLON) {
  62197. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62198. __extends(ColorCorrectionPostProcess, _super);
  62199. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62200. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62201. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62202. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62203. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62204. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62205. _this.onApply = function (effect) {
  62206. effect.setTexture("colorTable", _this._colorTableTexture);
  62207. };
  62208. return _this;
  62209. }
  62210. return ColorCorrectionPostProcess;
  62211. }(BABYLON.PostProcess));
  62212. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62213. })(BABYLON || (BABYLON = {}));
  62214. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62215. var BABYLON;
  62216. (function (BABYLON) {
  62217. var TonemappingOperator;
  62218. (function (TonemappingOperator) {
  62219. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62220. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62221. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62222. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62223. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62224. ;
  62225. var TonemapPostProcess = /** @class */ (function (_super) {
  62226. __extends(TonemapPostProcess, _super);
  62227. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62229. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62230. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62231. _this._operator = _operator;
  62232. _this.exposureAdjustment = exposureAdjustment;
  62233. var defines = "#define ";
  62234. if (_this._operator === TonemappingOperator.Hable)
  62235. defines += "HABLE_TONEMAPPING";
  62236. else if (_this._operator === TonemappingOperator.Reinhard)
  62237. defines += "REINHARD_TONEMAPPING";
  62238. else if (_this._operator === TonemappingOperator.HejiDawson)
  62239. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62240. else if (_this._operator === TonemappingOperator.Photographic)
  62241. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62242. //sadly a second call to create the effect.
  62243. _this.updateEffect(defines);
  62244. _this.onApply = function (effect) {
  62245. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62246. };
  62247. return _this;
  62248. }
  62249. return TonemapPostProcess;
  62250. }(BABYLON.PostProcess));
  62251. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62252. })(BABYLON || (BABYLON = {}));
  62253. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62254. var BABYLON;
  62255. (function (BABYLON) {
  62256. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62257. __extends(DisplayPassPostProcess, _super);
  62258. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62259. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62260. }
  62261. return DisplayPassPostProcess;
  62262. }(BABYLON.PostProcess));
  62263. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62264. })(BABYLON || (BABYLON = {}));
  62265. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62266. var BABYLON;
  62267. (function (BABYLON) {
  62268. var HighlightsPostProcess = /** @class */ (function (_super) {
  62269. __extends(HighlightsPostProcess, _super);
  62270. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62271. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62272. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62273. }
  62274. return HighlightsPostProcess;
  62275. }(BABYLON.PostProcess));
  62276. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62277. })(BABYLON || (BABYLON = {}));
  62278. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62279. var BABYLON;
  62280. (function (BABYLON) {
  62281. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62282. __extends(ImageProcessingPostProcess, _super);
  62283. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62284. if (camera === void 0) { camera = null; }
  62285. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62286. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62287. _this._fromLinearSpace = true;
  62288. /**
  62289. * Defines cache preventing GC.
  62290. */
  62291. _this._defines = {
  62292. IMAGEPROCESSING: false,
  62293. VIGNETTE: false,
  62294. VIGNETTEBLENDMODEMULTIPLY: false,
  62295. VIGNETTEBLENDMODEOPAQUE: false,
  62296. TONEMAPPING: false,
  62297. CONTRAST: false,
  62298. COLORCURVES: false,
  62299. COLORGRADING: false,
  62300. COLORGRADING3D: false,
  62301. FROMLINEARSPACE: false,
  62302. SAMPLER3DGREENDEPTH: false,
  62303. SAMPLER3DBGRMAP: false,
  62304. IMAGEPROCESSINGPOSTPROCESS: false,
  62305. EXPOSURE: false,
  62306. };
  62307. // Setup the configuration as forced by the constructor. This would then not force the
  62308. // scene materials output in linear space and let untouched the default forward pass.
  62309. if (imageProcessingConfiguration) {
  62310. imageProcessingConfiguration.applyByPostProcess = true;
  62311. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62312. // This will cause the shader to be compiled
  62313. _this.fromLinearSpace = false;
  62314. }
  62315. else {
  62316. _this._attachImageProcessingConfiguration(null, true);
  62317. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62318. }
  62319. _this.onApply = function (effect) {
  62320. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62321. };
  62322. return _this;
  62323. }
  62324. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62325. /**
  62326. * Gets the image processing configuration used either in this material.
  62327. */
  62328. get: function () {
  62329. return this._imageProcessingConfiguration;
  62330. },
  62331. /**
  62332. * Sets the Default image processing configuration used either in the this material.
  62333. *
  62334. * If sets to null, the scene one is in use.
  62335. */
  62336. set: function (value) {
  62337. this._attachImageProcessingConfiguration(value);
  62338. },
  62339. enumerable: true,
  62340. configurable: true
  62341. });
  62342. /**
  62343. * Attaches a new image processing configuration to the PBR Material.
  62344. * @param configuration
  62345. */
  62346. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62347. var _this = this;
  62348. if (doNotBuild === void 0) { doNotBuild = false; }
  62349. if (configuration === this._imageProcessingConfiguration) {
  62350. return;
  62351. }
  62352. // Detaches observer.
  62353. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62354. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62355. }
  62356. // Pick the scene configuration if needed.
  62357. if (!configuration) {
  62358. var scene = null;
  62359. var engine = this.getEngine();
  62360. var camera = this.getCamera();
  62361. if (camera) {
  62362. scene = camera.getScene();
  62363. }
  62364. else if (engine && engine.scenes) {
  62365. var scenes = engine.scenes;
  62366. scene = scenes[scenes.length - 1];
  62367. }
  62368. else {
  62369. scene = BABYLON.Engine.LastCreatedScene;
  62370. }
  62371. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62372. }
  62373. else {
  62374. this._imageProcessingConfiguration = configuration;
  62375. }
  62376. // Attaches observer.
  62377. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62378. _this._updateParameters();
  62379. });
  62380. // Ensure the effect will be rebuilt.
  62381. if (!doNotBuild) {
  62382. this._updateParameters();
  62383. }
  62384. };
  62385. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62386. /**
  62387. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62388. */
  62389. get: function () {
  62390. return this.imageProcessingConfiguration.colorCurves;
  62391. },
  62392. /**
  62393. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62394. */
  62395. set: function (value) {
  62396. this.imageProcessingConfiguration.colorCurves = value;
  62397. },
  62398. enumerable: true,
  62399. configurable: true
  62400. });
  62401. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62402. /**
  62403. * Gets wether the color curves effect is enabled.
  62404. */
  62405. get: function () {
  62406. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62407. },
  62408. /**
  62409. * Sets wether the color curves effect is enabled.
  62410. */
  62411. set: function (value) {
  62412. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62413. },
  62414. enumerable: true,
  62415. configurable: true
  62416. });
  62417. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62418. /**
  62419. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62420. */
  62421. get: function () {
  62422. return this.imageProcessingConfiguration.colorGradingTexture;
  62423. },
  62424. /**
  62425. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62426. */
  62427. set: function (value) {
  62428. this.imageProcessingConfiguration.colorGradingTexture = value;
  62429. },
  62430. enumerable: true,
  62431. configurable: true
  62432. });
  62433. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62434. /**
  62435. * Gets wether the color grading effect is enabled.
  62436. */
  62437. get: function () {
  62438. return this.imageProcessingConfiguration.colorGradingEnabled;
  62439. },
  62440. /**
  62441. * Gets wether the color grading effect is enabled.
  62442. */
  62443. set: function (value) {
  62444. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62445. },
  62446. enumerable: true,
  62447. configurable: true
  62448. });
  62449. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62450. /**
  62451. * Gets exposure used in the effect.
  62452. */
  62453. get: function () {
  62454. return this.imageProcessingConfiguration.exposure;
  62455. },
  62456. /**
  62457. * Sets exposure used in the effect.
  62458. */
  62459. set: function (value) {
  62460. this.imageProcessingConfiguration.exposure = value;
  62461. },
  62462. enumerable: true,
  62463. configurable: true
  62464. });
  62465. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62466. /**
  62467. * Gets wether tonemapping is enabled or not.
  62468. */
  62469. get: function () {
  62470. return this._imageProcessingConfiguration.toneMappingEnabled;
  62471. },
  62472. /**
  62473. * Sets wether tonemapping is enabled or not
  62474. */
  62475. set: function (value) {
  62476. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62477. },
  62478. enumerable: true,
  62479. configurable: true
  62480. });
  62481. ;
  62482. ;
  62483. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62484. /**
  62485. * Gets contrast used in the effect.
  62486. */
  62487. get: function () {
  62488. return this.imageProcessingConfiguration.contrast;
  62489. },
  62490. /**
  62491. * Sets contrast used in the effect.
  62492. */
  62493. set: function (value) {
  62494. this.imageProcessingConfiguration.contrast = value;
  62495. },
  62496. enumerable: true,
  62497. configurable: true
  62498. });
  62499. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62500. /**
  62501. * Gets Vignette stretch size.
  62502. */
  62503. get: function () {
  62504. return this.imageProcessingConfiguration.vignetteStretch;
  62505. },
  62506. /**
  62507. * Sets Vignette stretch size.
  62508. */
  62509. set: function (value) {
  62510. this.imageProcessingConfiguration.vignetteStretch = value;
  62511. },
  62512. enumerable: true,
  62513. configurable: true
  62514. });
  62515. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62516. /**
  62517. * Gets Vignette centre X Offset.
  62518. */
  62519. get: function () {
  62520. return this.imageProcessingConfiguration.vignetteCentreX;
  62521. },
  62522. /**
  62523. * Sets Vignette centre X Offset.
  62524. */
  62525. set: function (value) {
  62526. this.imageProcessingConfiguration.vignetteCentreX = value;
  62527. },
  62528. enumerable: true,
  62529. configurable: true
  62530. });
  62531. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62532. /**
  62533. * Gets Vignette centre Y Offset.
  62534. */
  62535. get: function () {
  62536. return this.imageProcessingConfiguration.vignetteCentreY;
  62537. },
  62538. /**
  62539. * Sets Vignette centre Y Offset.
  62540. */
  62541. set: function (value) {
  62542. this.imageProcessingConfiguration.vignetteCentreY = value;
  62543. },
  62544. enumerable: true,
  62545. configurable: true
  62546. });
  62547. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62548. /**
  62549. * Gets Vignette weight or intensity of the vignette effect.
  62550. */
  62551. get: function () {
  62552. return this.imageProcessingConfiguration.vignetteWeight;
  62553. },
  62554. /**
  62555. * Sets Vignette weight or intensity of the vignette effect.
  62556. */
  62557. set: function (value) {
  62558. this.imageProcessingConfiguration.vignetteWeight = value;
  62559. },
  62560. enumerable: true,
  62561. configurable: true
  62562. });
  62563. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62564. /**
  62565. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62566. * if vignetteEnabled is set to true.
  62567. */
  62568. get: function () {
  62569. return this.imageProcessingConfiguration.vignetteColor;
  62570. },
  62571. /**
  62572. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62573. * if vignetteEnabled is set to true.
  62574. */
  62575. set: function (value) {
  62576. this.imageProcessingConfiguration.vignetteColor = value;
  62577. },
  62578. enumerable: true,
  62579. configurable: true
  62580. });
  62581. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62582. /**
  62583. * Gets Camera field of view used by the Vignette effect.
  62584. */
  62585. get: function () {
  62586. return this.imageProcessingConfiguration.vignetteCameraFov;
  62587. },
  62588. /**
  62589. * Sets Camera field of view used by the Vignette effect.
  62590. */
  62591. set: function (value) {
  62592. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62593. },
  62594. enumerable: true,
  62595. configurable: true
  62596. });
  62597. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62598. /**
  62599. * Gets the vignette blend mode allowing different kind of effect.
  62600. */
  62601. get: function () {
  62602. return this.imageProcessingConfiguration.vignetteBlendMode;
  62603. },
  62604. /**
  62605. * Sets the vignette blend mode allowing different kind of effect.
  62606. */
  62607. set: function (value) {
  62608. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62609. },
  62610. enumerable: true,
  62611. configurable: true
  62612. });
  62613. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62614. /**
  62615. * Gets wether the vignette effect is enabled.
  62616. */
  62617. get: function () {
  62618. return this.imageProcessingConfiguration.vignetteEnabled;
  62619. },
  62620. /**
  62621. * Sets wether the vignette effect is enabled.
  62622. */
  62623. set: function (value) {
  62624. this.imageProcessingConfiguration.vignetteEnabled = value;
  62625. },
  62626. enumerable: true,
  62627. configurable: true
  62628. });
  62629. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62630. /**
  62631. * Gets wether the input of the processing is in Gamma or Linear Space.
  62632. */
  62633. get: function () {
  62634. return this._fromLinearSpace;
  62635. },
  62636. /**
  62637. * Sets wether the input of the processing is in Gamma or Linear Space.
  62638. */
  62639. set: function (value) {
  62640. if (this._fromLinearSpace === value) {
  62641. return;
  62642. }
  62643. this._fromLinearSpace = value;
  62644. this._updateParameters();
  62645. },
  62646. enumerable: true,
  62647. configurable: true
  62648. });
  62649. ImageProcessingPostProcess.prototype.getClassName = function () {
  62650. return "ImageProcessingPostProcess";
  62651. };
  62652. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62653. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62654. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62655. var defines = "";
  62656. for (var define in this._defines) {
  62657. if (this._defines[define]) {
  62658. defines += "#define " + define + ";\r\n";
  62659. }
  62660. }
  62661. var samplers = ["textureSampler"];
  62662. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62663. var uniforms = ["scale"];
  62664. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62665. this.updateEffect(defines, uniforms, samplers);
  62666. };
  62667. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62668. _super.prototype.dispose.call(this, camera);
  62669. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62670. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62671. }
  62672. this.imageProcessingConfiguration.applyByPostProcess = false;
  62673. };
  62674. __decorate([
  62675. BABYLON.serialize()
  62676. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62677. return ImageProcessingPostProcess;
  62678. }(BABYLON.PostProcess));
  62679. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62680. })(BABYLON || (BABYLON = {}));
  62681. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62682. var BABYLON;
  62683. (function (BABYLON) {
  62684. var BlurPostProcess = /** @class */ (function (_super) {
  62685. __extends(BlurPostProcess, _super);
  62686. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62688. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62689. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62690. _this.direction = direction;
  62691. _this._packedFloat = false;
  62692. _this.onApplyObservable.add(function (effect) {
  62693. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62694. });
  62695. _this.kernel = kernel;
  62696. return _this;
  62697. }
  62698. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  62699. /**
  62700. * Gets the length in pixels of the blur sample region
  62701. */
  62702. get: function () {
  62703. return this._idealKernel;
  62704. },
  62705. /**
  62706. * Sets the length in pixels of the blur sample region
  62707. */
  62708. set: function (v) {
  62709. if (this._idealKernel === v) {
  62710. return;
  62711. }
  62712. v = Math.max(v, 1);
  62713. this._idealKernel = v;
  62714. this._kernel = this._nearestBestKernel(v);
  62715. this._updateParameters();
  62716. },
  62717. enumerable: true,
  62718. configurable: true
  62719. });
  62720. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  62721. /**
  62722. * Gets wether or not the blur is unpacking/repacking floats
  62723. */
  62724. get: function () {
  62725. return this._packedFloat;
  62726. },
  62727. /**
  62728. * Sets wether or not the blur needs to unpack/repack floats
  62729. */
  62730. set: function (v) {
  62731. if (this._packedFloat === v) {
  62732. return;
  62733. }
  62734. this._packedFloat = v;
  62735. this._updateParameters();
  62736. },
  62737. enumerable: true,
  62738. configurable: true
  62739. });
  62740. BlurPostProcess.prototype._updateParameters = function () {
  62741. // Generate sampling offsets and weights
  62742. var N = this._kernel;
  62743. var centerIndex = (N - 1) / 2;
  62744. // Generate Gaussian sampling weights over kernel
  62745. var offsets = [];
  62746. var weights = [];
  62747. var totalWeight = 0;
  62748. for (var i = 0; i < N; i++) {
  62749. var u = i / (N - 1);
  62750. var w = this._gaussianWeight(u * 2.0 - 1);
  62751. offsets[i] = (i - centerIndex);
  62752. weights[i] = w;
  62753. totalWeight += w;
  62754. }
  62755. // Normalize weights
  62756. for (var i = 0; i < weights.length; i++) {
  62757. weights[i] /= totalWeight;
  62758. }
  62759. // Optimize: combine samples to take advantage of hardware linear sampling
  62760. // Walk from left to center, combining pairs (symmetrically)
  62761. var linearSamplingWeights = [];
  62762. var linearSamplingOffsets = [];
  62763. var linearSamplingMap = [];
  62764. for (var i = 0; i <= centerIndex; i += 2) {
  62765. var j = Math.min(i + 1, Math.floor(centerIndex));
  62766. var singleCenterSample = i === j;
  62767. if (singleCenterSample) {
  62768. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  62769. }
  62770. else {
  62771. var sharedCell = j === centerIndex;
  62772. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  62773. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  62774. if (offsetLinear === 0) {
  62775. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  62776. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  62777. }
  62778. else {
  62779. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  62780. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  62781. }
  62782. }
  62783. }
  62784. for (var i = 0; i < linearSamplingMap.length; i++) {
  62785. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  62786. linearSamplingWeights[i] = linearSamplingMap[i].w;
  62787. }
  62788. // Replace with optimized
  62789. offsets = linearSamplingOffsets;
  62790. weights = linearSamplingWeights;
  62791. // Generate shaders
  62792. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  62793. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  62794. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  62795. var defines = "";
  62796. for (var i = 0; i < varyingCount; i++) {
  62797. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  62798. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  62799. }
  62800. var depCount = 0;
  62801. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  62802. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  62803. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  62804. depCount++;
  62805. }
  62806. if (this.packedFloat) {
  62807. defines += "#define PACKEDFLOAT 1";
  62808. }
  62809. this.updateEffect(defines, null, null, {
  62810. varyingCount: varyingCount,
  62811. depCount: depCount
  62812. });
  62813. };
  62814. /**
  62815. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  62816. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  62817. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  62818. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  62819. * The gaps between physical kernels are compensated for in the weighting of the samples
  62820. * @param idealKernel Ideal blur kernel.
  62821. * @return Nearest best kernel.
  62822. */
  62823. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  62824. var v = Math.round(idealKernel);
  62825. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  62826. var k = _a[_i];
  62827. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  62828. return Math.max(k, 3);
  62829. }
  62830. }
  62831. return Math.max(v, 3);
  62832. };
  62833. /**
  62834. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  62835. * @param x The point on the Gaussian distribution to sample.
  62836. * @return the value of the Gaussian function at x.
  62837. */
  62838. BlurPostProcess.prototype._gaussianWeight = function (x) {
  62839. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  62840. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  62841. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  62842. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  62843. // truncated at around 1.3% of peak strength.
  62844. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  62845. var sigma = (1 / 3);
  62846. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  62847. var exponent = -((x * x) / (2.0 * sigma * sigma));
  62848. var weight = (1.0 / denominator) * Math.exp(exponent);
  62849. return weight;
  62850. };
  62851. /**
  62852. * Generates a string that can be used as a floating point number in GLSL.
  62853. * @param x Value to print.
  62854. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  62855. * @return GLSL float string.
  62856. */
  62857. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  62858. if (decimalFigures === void 0) { decimalFigures = 8; }
  62859. return x.toFixed(decimalFigures).replace(/0+$/, '');
  62860. };
  62861. return BlurPostProcess;
  62862. }(BABYLON.PostProcess));
  62863. BABYLON.BlurPostProcess = BlurPostProcess;
  62864. })(BABYLON || (BABYLON = {}));
  62865. //# sourceMappingURL=babylon.blurPostProcess.js.map
  62866. var BABYLON;
  62867. (function (BABYLON) {
  62868. var Bone = /** @class */ (function (_super) {
  62869. __extends(Bone, _super);
  62870. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  62871. if (parentBone === void 0) { parentBone = null; }
  62872. if (localMatrix === void 0) { localMatrix = null; }
  62873. if (restPose === void 0) { restPose = null; }
  62874. if (baseMatrix === void 0) { baseMatrix = null; }
  62875. if (index === void 0) { index = null; }
  62876. var _this = _super.call(this, name, skeleton.getScene()) || this;
  62877. _this.name = name;
  62878. _this.children = new Array();
  62879. _this.animations = new Array();
  62880. // Set this value to map this bone to a different index in the transform matrices.
  62881. // Set this value to -1 to exclude the bone from the transform matrices.
  62882. _this._index = null;
  62883. _this._worldTransform = new BABYLON.Matrix();
  62884. _this._absoluteTransform = new BABYLON.Matrix();
  62885. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  62886. _this._scaleMatrix = BABYLON.Matrix.Identity();
  62887. _this._scaleVector = BABYLON.Vector3.One();
  62888. _this._negateScaleChildren = BABYLON.Vector3.One();
  62889. _this._scalingDeterminant = 1;
  62890. _this._skeleton = skeleton;
  62891. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  62892. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  62893. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  62894. _this._index = index;
  62895. skeleton.bones.push(_this);
  62896. _this.setParent(parentBone, false);
  62897. _this._updateDifferenceMatrix();
  62898. return _this;
  62899. }
  62900. Object.defineProperty(Bone.prototype, "_matrix", {
  62901. get: function () {
  62902. return this._localMatrix;
  62903. },
  62904. set: function (val) {
  62905. if (this._localMatrix) {
  62906. this._localMatrix.copyFrom(val);
  62907. }
  62908. else {
  62909. this._localMatrix = val;
  62910. }
  62911. },
  62912. enumerable: true,
  62913. configurable: true
  62914. });
  62915. // Members
  62916. Bone.prototype.getSkeleton = function () {
  62917. return this._skeleton;
  62918. };
  62919. Bone.prototype.getParent = function () {
  62920. return this._parent;
  62921. };
  62922. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  62923. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62924. if (this._parent === parent) {
  62925. return;
  62926. }
  62927. if (this._parent) {
  62928. var index = this._parent.children.indexOf(this);
  62929. if (index !== -1) {
  62930. this._parent.children.splice(index, 1);
  62931. }
  62932. }
  62933. this._parent = parent;
  62934. if (this._parent) {
  62935. this._parent.children.push(this);
  62936. }
  62937. if (updateDifferenceMatrix) {
  62938. this._updateDifferenceMatrix();
  62939. }
  62940. };
  62941. Bone.prototype.getLocalMatrix = function () {
  62942. return this._localMatrix;
  62943. };
  62944. Bone.prototype.getBaseMatrix = function () {
  62945. return this._baseMatrix;
  62946. };
  62947. Bone.prototype.getRestPose = function () {
  62948. return this._restPose;
  62949. };
  62950. Bone.prototype.returnToRest = function () {
  62951. this.updateMatrix(this._restPose.clone());
  62952. };
  62953. Bone.prototype.getWorldMatrix = function () {
  62954. return this._worldTransform;
  62955. };
  62956. Bone.prototype.getInvertedAbsoluteTransform = function () {
  62957. return this._invertedAbsoluteTransform;
  62958. };
  62959. Bone.prototype.getAbsoluteTransform = function () {
  62960. return this._absoluteTransform;
  62961. };
  62962. Object.defineProperty(Bone.prototype, "position", {
  62963. // Properties (matches AbstractMesh properties)
  62964. get: function () {
  62965. return this.getPosition();
  62966. },
  62967. set: function (newPosition) {
  62968. this.setPosition(newPosition);
  62969. },
  62970. enumerable: true,
  62971. configurable: true
  62972. });
  62973. Object.defineProperty(Bone.prototype, "rotation", {
  62974. get: function () {
  62975. return this.getRotation();
  62976. },
  62977. set: function (newRotation) {
  62978. this.setRotation(newRotation);
  62979. },
  62980. enumerable: true,
  62981. configurable: true
  62982. });
  62983. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  62984. get: function () {
  62985. return this.getRotationQuaternion();
  62986. },
  62987. set: function (newRotation) {
  62988. this.setRotationQuaternion(newRotation);
  62989. },
  62990. enumerable: true,
  62991. configurable: true
  62992. });
  62993. Object.defineProperty(Bone.prototype, "scaling", {
  62994. get: function () {
  62995. return this.getScale();
  62996. },
  62997. set: function (newScaling) {
  62998. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  62999. },
  63000. enumerable: true,
  63001. configurable: true
  63002. });
  63003. // Methods
  63004. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63005. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63006. this._baseMatrix = matrix.clone();
  63007. this._localMatrix = matrix.clone();
  63008. this._skeleton._markAsDirty();
  63009. if (updateDifferenceMatrix) {
  63010. this._updateDifferenceMatrix();
  63011. }
  63012. };
  63013. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63014. if (!rootMatrix) {
  63015. rootMatrix = this._baseMatrix;
  63016. }
  63017. if (this._parent) {
  63018. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63019. }
  63020. else {
  63021. this._absoluteTransform.copyFrom(rootMatrix);
  63022. }
  63023. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63024. for (var index = 0; index < this.children.length; index++) {
  63025. this.children[index]._updateDifferenceMatrix();
  63026. }
  63027. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63028. };
  63029. Bone.prototype.markAsDirty = function () {
  63030. this._currentRenderId++;
  63031. this._skeleton._markAsDirty();
  63032. };
  63033. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63034. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63035. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63036. // all animation may be coming from a library skeleton, so may need to create animation
  63037. if (this.animations.length === 0) {
  63038. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63039. this.animations[0].setKeys([]);
  63040. }
  63041. // get animation info / verify there is such a range from the source bone
  63042. var sourceRange = source.animations[0].getRange(rangeName);
  63043. if (!sourceRange) {
  63044. return false;
  63045. }
  63046. var from = sourceRange.from;
  63047. var to = sourceRange.to;
  63048. var sourceKeys = source.animations[0].getKeys();
  63049. // rescaling prep
  63050. var sourceBoneLength = source.length;
  63051. var sourceParent = source.getParent();
  63052. var parent = this.getParent();
  63053. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63054. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63055. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63056. var destKeys = this.animations[0].getKeys();
  63057. // loop vars declaration
  63058. var orig;
  63059. var origTranslation;
  63060. var mat;
  63061. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63062. orig = sourceKeys[key];
  63063. if (orig.frame >= from && orig.frame <= to) {
  63064. if (rescaleAsRequired) {
  63065. mat = orig.value.clone();
  63066. // scale based on parent ratio, when bone has parent
  63067. if (parentScalingReqd) {
  63068. origTranslation = mat.getTranslation();
  63069. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63070. // scale based on skeleton dimension ratio when root bone, and value is passed
  63071. }
  63072. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63073. origTranslation = mat.getTranslation();
  63074. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63075. // use original when root bone, and no data for skelDimensionsRatio
  63076. }
  63077. else {
  63078. mat = orig.value;
  63079. }
  63080. }
  63081. else {
  63082. mat = orig.value;
  63083. }
  63084. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63085. }
  63086. }
  63087. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63088. return true;
  63089. };
  63090. /**
  63091. * Translate the bone in local or world space.
  63092. * @param vec The amount to translate the bone.
  63093. * @param space The space that the translation is in.
  63094. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63095. */
  63096. Bone.prototype.translate = function (vec, space, mesh) {
  63097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63098. var lm = this.getLocalMatrix();
  63099. if (space == BABYLON.Space.LOCAL) {
  63100. lm.m[12] += vec.x;
  63101. lm.m[13] += vec.y;
  63102. lm.m[14] += vec.z;
  63103. }
  63104. else {
  63105. var wm = null;
  63106. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63107. if (mesh) {
  63108. wm = mesh.getWorldMatrix();
  63109. }
  63110. this._skeleton.computeAbsoluteTransforms();
  63111. var tmat = Bone._tmpMats[0];
  63112. var tvec = Bone._tmpVecs[0];
  63113. if (this._parent) {
  63114. if (mesh && wm) {
  63115. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63116. tmat.multiplyToRef(wm, tmat);
  63117. }
  63118. else {
  63119. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63120. }
  63121. }
  63122. tmat.m[12] = 0;
  63123. tmat.m[13] = 0;
  63124. tmat.m[14] = 0;
  63125. tmat.invert();
  63126. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63127. lm.m[12] += tvec.x;
  63128. lm.m[13] += tvec.y;
  63129. lm.m[14] += tvec.z;
  63130. }
  63131. this.markAsDirty();
  63132. };
  63133. /**
  63134. * Set the postion of the bone in local or world space.
  63135. * @param position The position to set the bone.
  63136. * @param space The space that the position is in.
  63137. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63138. */
  63139. Bone.prototype.setPosition = function (position, space, mesh) {
  63140. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63141. var lm = this.getLocalMatrix();
  63142. if (space == BABYLON.Space.LOCAL) {
  63143. lm.m[12] = position.x;
  63144. lm.m[13] = position.y;
  63145. lm.m[14] = position.z;
  63146. }
  63147. else {
  63148. var wm = null;
  63149. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63150. if (mesh) {
  63151. wm = mesh.getWorldMatrix();
  63152. }
  63153. this._skeleton.computeAbsoluteTransforms();
  63154. var tmat = Bone._tmpMats[0];
  63155. var vec = Bone._tmpVecs[0];
  63156. if (this._parent) {
  63157. if (mesh && wm) {
  63158. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63159. tmat.multiplyToRef(wm, tmat);
  63160. }
  63161. else {
  63162. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63163. }
  63164. }
  63165. tmat.invert();
  63166. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63167. lm.m[12] = vec.x;
  63168. lm.m[13] = vec.y;
  63169. lm.m[14] = vec.z;
  63170. }
  63171. this.markAsDirty();
  63172. };
  63173. /**
  63174. * Set the absolute postion of the bone (world space).
  63175. * @param position The position to set the bone.
  63176. * @param mesh The mesh that this bone is attached to.
  63177. */
  63178. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63179. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63180. };
  63181. /**
  63182. * Set the scale of the bone on the x, y and z axes.
  63183. * @param x The scale of the bone on the x axis.
  63184. * @param x The scale of the bone on the y axis.
  63185. * @param z The scale of the bone on the z axis.
  63186. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63187. */
  63188. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63189. if (scaleChildren === void 0) { scaleChildren = false; }
  63190. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63191. if (!scaleChildren) {
  63192. this._negateScaleChildren.x = 1 / x;
  63193. this._negateScaleChildren.y = 1 / y;
  63194. this._negateScaleChildren.z = 1 / z;
  63195. }
  63196. this._syncScaleVector();
  63197. }
  63198. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63199. };
  63200. /**
  63201. * Scale the bone on the x, y and z axes.
  63202. * @param x The amount to scale the bone on the x axis.
  63203. * @param x The amount to scale the bone on the y axis.
  63204. * @param z The amount to scale the bone on the z axis.
  63205. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63206. */
  63207. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63208. if (scaleChildren === void 0) { scaleChildren = false; }
  63209. var locMat = this.getLocalMatrix();
  63210. var origLocMat = Bone._tmpMats[0];
  63211. origLocMat.copyFrom(locMat);
  63212. var origLocMatInv = Bone._tmpMats[1];
  63213. origLocMatInv.copyFrom(origLocMat);
  63214. origLocMatInv.invert();
  63215. var scaleMat = Bone._tmpMats[2];
  63216. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63217. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63218. this._scaleVector.x *= x;
  63219. this._scaleVector.y *= y;
  63220. this._scaleVector.z *= z;
  63221. locMat.multiplyToRef(origLocMatInv, locMat);
  63222. locMat.multiplyToRef(scaleMat, locMat);
  63223. locMat.multiplyToRef(origLocMat, locMat);
  63224. var parent = this.getParent();
  63225. if (parent) {
  63226. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63227. }
  63228. else {
  63229. this.getAbsoluteTransform().copyFrom(locMat);
  63230. }
  63231. var len = this.children.length;
  63232. scaleMat.invert();
  63233. for (var i = 0; i < len; i++) {
  63234. var child = this.children[i];
  63235. var cm = child.getLocalMatrix();
  63236. cm.multiplyToRef(scaleMat, cm);
  63237. var lm = child.getLocalMatrix();
  63238. lm.m[12] *= x;
  63239. lm.m[13] *= y;
  63240. lm.m[14] *= z;
  63241. }
  63242. this.computeAbsoluteTransforms();
  63243. if (scaleChildren) {
  63244. for (var i = 0; i < len; i++) {
  63245. this.children[i].scale(x, y, z, scaleChildren);
  63246. }
  63247. }
  63248. this.markAsDirty();
  63249. };
  63250. /**
  63251. * Set the yaw, pitch, and roll of the bone in local or world space.
  63252. * @param yaw The rotation of the bone on the y axis.
  63253. * @param pitch The rotation of the bone on the x axis.
  63254. * @param roll The rotation of the bone on the z axis.
  63255. * @param space The space that the axes of rotation are in.
  63256. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63257. */
  63258. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63260. var rotMat = Bone._tmpMats[0];
  63261. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63262. var rotMatInv = Bone._tmpMats[1];
  63263. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63264. rotMatInv.multiplyToRef(rotMat, rotMat);
  63265. this._rotateWithMatrix(rotMat, space, mesh);
  63266. };
  63267. /**
  63268. * Rotate the bone on an axis in local or world space.
  63269. * @param axis The axis to rotate the bone on.
  63270. * @param amount The amount to rotate the bone.
  63271. * @param space The space that the axis is in.
  63272. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63273. */
  63274. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63275. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63276. var rmat = Bone._tmpMats[0];
  63277. rmat.m[12] = 0;
  63278. rmat.m[13] = 0;
  63279. rmat.m[14] = 0;
  63280. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63281. this._rotateWithMatrix(rmat, space, mesh);
  63282. };
  63283. /**
  63284. * Set the rotation of the bone to a particular axis angle in local or world space.
  63285. * @param axis The axis to rotate the bone on.
  63286. * @param angle The angle that the bone should be rotated to.
  63287. * @param space The space that the axis is in.
  63288. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63289. */
  63290. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63292. var rotMat = Bone._tmpMats[0];
  63293. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63294. var rotMatInv = Bone._tmpMats[1];
  63295. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63296. rotMatInv.multiplyToRef(rotMat, rotMat);
  63297. this._rotateWithMatrix(rotMat, space, mesh);
  63298. };
  63299. /**
  63300. * Set the euler rotation of the bone in local of world space.
  63301. * @param rotation The euler rotation that the bone should be set to.
  63302. * @param space The space that the rotation is in.
  63303. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63304. */
  63305. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63306. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63307. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63308. };
  63309. /**
  63310. * Set the quaternion rotation of the bone in local of world space.
  63311. * @param quat The quaternion rotation that the bone should be set to.
  63312. * @param space The space that the rotation is in.
  63313. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63314. */
  63315. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63316. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63317. var rotMatInv = Bone._tmpMats[0];
  63318. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63319. var rotMat = Bone._tmpMats[1];
  63320. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63321. rotMatInv.multiplyToRef(rotMat, rotMat);
  63322. this._rotateWithMatrix(rotMat, space, mesh);
  63323. };
  63324. /**
  63325. * Set the rotation matrix of the bone in local of world space.
  63326. * @param rotMat The rotation matrix that the bone should be set to.
  63327. * @param space The space that the rotation is in.
  63328. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63329. */
  63330. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63331. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63332. var rotMatInv = Bone._tmpMats[0];
  63333. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63334. var rotMat2 = Bone._tmpMats[1];
  63335. rotMat2.copyFrom(rotMat);
  63336. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63337. this._rotateWithMatrix(rotMat2, space, mesh);
  63338. };
  63339. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63340. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63341. var lmat = this.getLocalMatrix();
  63342. var lx = lmat.m[12];
  63343. var ly = lmat.m[13];
  63344. var lz = lmat.m[14];
  63345. var parent = this.getParent();
  63346. var parentScale = Bone._tmpMats[3];
  63347. var parentScaleInv = Bone._tmpMats[4];
  63348. if (parent) {
  63349. if (space == BABYLON.Space.WORLD) {
  63350. if (mesh) {
  63351. parentScale.copyFrom(mesh.getWorldMatrix());
  63352. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63353. }
  63354. else {
  63355. parentScale.copyFrom(parent.getAbsoluteTransform());
  63356. }
  63357. }
  63358. else {
  63359. parentScale = parent._scaleMatrix;
  63360. }
  63361. parentScaleInv.copyFrom(parentScale);
  63362. parentScaleInv.invert();
  63363. lmat.multiplyToRef(parentScale, lmat);
  63364. lmat.multiplyToRef(rmat, lmat);
  63365. lmat.multiplyToRef(parentScaleInv, lmat);
  63366. }
  63367. else {
  63368. if (space == BABYLON.Space.WORLD && mesh) {
  63369. parentScale.copyFrom(mesh.getWorldMatrix());
  63370. parentScaleInv.copyFrom(parentScale);
  63371. parentScaleInv.invert();
  63372. lmat.multiplyToRef(parentScale, lmat);
  63373. lmat.multiplyToRef(rmat, lmat);
  63374. lmat.multiplyToRef(parentScaleInv, lmat);
  63375. }
  63376. else {
  63377. lmat.multiplyToRef(rmat, lmat);
  63378. }
  63379. }
  63380. lmat.m[12] = lx;
  63381. lmat.m[13] = ly;
  63382. lmat.m[14] = lz;
  63383. this.computeAbsoluteTransforms();
  63384. this.markAsDirty();
  63385. };
  63386. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63388. if (space == BABYLON.Space.WORLD) {
  63389. var scaleMatrix = Bone._tmpMats[2];
  63390. scaleMatrix.copyFrom(this._scaleMatrix);
  63391. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63392. if (mesh) {
  63393. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63394. var meshScale = Bone._tmpMats[3];
  63395. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63396. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63397. }
  63398. rotMatInv.invert();
  63399. scaleMatrix.m[0] *= this._scalingDeterminant;
  63400. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63401. }
  63402. else {
  63403. rotMatInv.copyFrom(this.getLocalMatrix());
  63404. rotMatInv.invert();
  63405. var scaleMatrix = Bone._tmpMats[2];
  63406. scaleMatrix.copyFrom(this._scaleMatrix);
  63407. if (this._parent) {
  63408. var pscaleMatrix = Bone._tmpMats[3];
  63409. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63410. pscaleMatrix.invert();
  63411. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63412. }
  63413. else {
  63414. scaleMatrix.m[0] *= this._scalingDeterminant;
  63415. }
  63416. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63417. }
  63418. };
  63419. /**
  63420. * Get the scale of the bone
  63421. * @returns the scale of the bone
  63422. */
  63423. Bone.prototype.getScale = function () {
  63424. return this._scaleVector.clone();
  63425. };
  63426. /**
  63427. * Copy the scale of the bone to a vector3.
  63428. * @param result The vector3 to copy the scale to
  63429. */
  63430. Bone.prototype.getScaleToRef = function (result) {
  63431. result.copyFrom(this._scaleVector);
  63432. };
  63433. /**
  63434. * Get the position of the bone in local or world space.
  63435. * @param space The space that the returned position is in.
  63436. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63437. * @returns The position of the bone
  63438. */
  63439. Bone.prototype.getPosition = function (space, mesh) {
  63440. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63441. if (mesh === void 0) { mesh = null; }
  63442. var pos = BABYLON.Vector3.Zero();
  63443. this.getPositionToRef(space, mesh, pos);
  63444. return pos;
  63445. };
  63446. /**
  63447. * Copy the position of the bone to a vector3 in local or world space.
  63448. * @param space The space that the returned position is in.
  63449. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63450. * @param result The vector3 to copy the position to.
  63451. */
  63452. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63454. if (space == BABYLON.Space.LOCAL) {
  63455. var lm = this.getLocalMatrix();
  63456. result.x = lm.m[12];
  63457. result.y = lm.m[13];
  63458. result.z = lm.m[14];
  63459. }
  63460. else {
  63461. var wm = null;
  63462. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63463. if (mesh) {
  63464. wm = mesh.getWorldMatrix();
  63465. }
  63466. this._skeleton.computeAbsoluteTransforms();
  63467. var tmat = Bone._tmpMats[0];
  63468. if (mesh && wm) {
  63469. tmat.copyFrom(this.getAbsoluteTransform());
  63470. tmat.multiplyToRef(wm, tmat);
  63471. }
  63472. else {
  63473. tmat = this.getAbsoluteTransform();
  63474. }
  63475. result.x = tmat.m[12];
  63476. result.y = tmat.m[13];
  63477. result.z = tmat.m[14];
  63478. }
  63479. };
  63480. /**
  63481. * Get the absolute position of the bone (world space).
  63482. * @param mesh The mesh that this bone is attached to.
  63483. * @returns The absolute position of the bone
  63484. */
  63485. Bone.prototype.getAbsolutePosition = function (mesh) {
  63486. if (mesh === void 0) { mesh = null; }
  63487. var pos = BABYLON.Vector3.Zero();
  63488. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63489. return pos;
  63490. };
  63491. /**
  63492. * Copy the absolute position of the bone (world space) to the result param.
  63493. * @param mesh The mesh that this bone is attached to.
  63494. * @param result The vector3 to copy the absolute position to.
  63495. */
  63496. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63497. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63498. };
  63499. /**
  63500. * Compute the absolute transforms of this bone and its children.
  63501. */
  63502. Bone.prototype.computeAbsoluteTransforms = function () {
  63503. if (this._parent) {
  63504. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63505. }
  63506. else {
  63507. this._absoluteTransform.copyFrom(this._localMatrix);
  63508. var poseMatrix = this._skeleton.getPoseMatrix();
  63509. if (poseMatrix) {
  63510. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63511. }
  63512. }
  63513. var children = this.children;
  63514. var len = children.length;
  63515. for (var i = 0; i < len; i++) {
  63516. children[i].computeAbsoluteTransforms();
  63517. }
  63518. };
  63519. Bone.prototype._syncScaleVector = function () {
  63520. var lm = this.getLocalMatrix();
  63521. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63522. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63523. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63524. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63525. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63526. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63527. this._scaleVector.x = xs * Math.sqrt(xsq);
  63528. this._scaleVector.y = ys * Math.sqrt(ysq);
  63529. this._scaleVector.z = zs * Math.sqrt(zsq);
  63530. if (this._parent) {
  63531. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63532. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63533. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63534. }
  63535. 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);
  63536. };
  63537. /**
  63538. * Get the world direction from an axis that is in the local space of the bone.
  63539. * @param localAxis The local direction that is used to compute the world direction.
  63540. * @param mesh The mesh that this bone is attached to.
  63541. * @returns The world direction
  63542. */
  63543. Bone.prototype.getDirection = function (localAxis, mesh) {
  63544. if (mesh === void 0) { mesh = null; }
  63545. var result = BABYLON.Vector3.Zero();
  63546. this.getDirectionToRef(localAxis, mesh, result);
  63547. return result;
  63548. };
  63549. /**
  63550. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63551. * @param localAxis The local direction that is used to compute the world direction.
  63552. * @param mesh The mesh that this bone is attached to.
  63553. * @param result The vector3 that the world direction will be copied to.
  63554. */
  63555. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63556. if (mesh === void 0) { mesh = null; }
  63557. var wm = null;
  63558. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63559. if (mesh) {
  63560. wm = mesh.getWorldMatrix();
  63561. }
  63562. this._skeleton.computeAbsoluteTransforms();
  63563. var mat = Bone._tmpMats[0];
  63564. mat.copyFrom(this.getAbsoluteTransform());
  63565. if (mesh && wm) {
  63566. mat.multiplyToRef(wm, mat);
  63567. }
  63568. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63569. result.normalize();
  63570. };
  63571. /**
  63572. * Get the euler rotation of the bone in local or world space.
  63573. * @param space The space that the rotation should be in.
  63574. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63575. * @returns The euler rotation
  63576. */
  63577. Bone.prototype.getRotation = function (space, mesh) {
  63578. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63579. if (mesh === void 0) { mesh = null; }
  63580. var result = BABYLON.Vector3.Zero();
  63581. this.getRotationToRef(space, mesh, result);
  63582. return result;
  63583. };
  63584. /**
  63585. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63586. * @param space The space that the rotation should be in.
  63587. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63588. * @param result The vector3 that the rotation should be copied to.
  63589. */
  63590. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63592. if (mesh === void 0) { mesh = null; }
  63593. var quat = Bone._tmpQuat;
  63594. this.getRotationQuaternionToRef(space, mesh, quat);
  63595. quat.toEulerAnglesToRef(result);
  63596. };
  63597. /**
  63598. * Get the quaternion rotation of the bone in either local or world space.
  63599. * @param space The space that the rotation should be in.
  63600. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63601. * @returns The quaternion rotation
  63602. */
  63603. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63605. if (mesh === void 0) { mesh = null; }
  63606. var result = BABYLON.Quaternion.Identity();
  63607. this.getRotationQuaternionToRef(space, mesh, result);
  63608. return result;
  63609. };
  63610. /**
  63611. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63612. * @param space The space that the rotation should be in.
  63613. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63614. * @param result The quaternion that the rotation should be copied to.
  63615. */
  63616. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63618. if (mesh === void 0) { mesh = null; }
  63619. if (space == BABYLON.Space.LOCAL) {
  63620. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63621. }
  63622. else {
  63623. var mat = Bone._tmpMats[0];
  63624. var amat = this.getAbsoluteTransform();
  63625. if (mesh) {
  63626. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63627. }
  63628. else {
  63629. mat.copyFrom(amat);
  63630. }
  63631. mat.m[0] *= this._scalingDeterminant;
  63632. mat.m[1] *= this._scalingDeterminant;
  63633. mat.m[2] *= this._scalingDeterminant;
  63634. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63635. }
  63636. };
  63637. /**
  63638. * Get the rotation matrix of the bone in local or world space.
  63639. * @param space The space that the rotation should be in.
  63640. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63641. * @returns The rotation matrix
  63642. */
  63643. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63644. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63645. var result = BABYLON.Matrix.Identity();
  63646. this.getRotationMatrixToRef(space, mesh, result);
  63647. return result;
  63648. };
  63649. /**
  63650. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63651. * @param space The space that the rotation should be in.
  63652. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63653. * @param result The quaternion that the rotation should be copied to.
  63654. */
  63655. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63657. if (space == BABYLON.Space.LOCAL) {
  63658. this.getLocalMatrix().getRotationMatrixToRef(result);
  63659. }
  63660. else {
  63661. var mat = Bone._tmpMats[0];
  63662. var amat = this.getAbsoluteTransform();
  63663. if (mesh) {
  63664. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63665. }
  63666. else {
  63667. mat.copyFrom(amat);
  63668. }
  63669. mat.m[0] *= this._scalingDeterminant;
  63670. mat.m[1] *= this._scalingDeterminant;
  63671. mat.m[2] *= this._scalingDeterminant;
  63672. mat.getRotationMatrixToRef(result);
  63673. }
  63674. };
  63675. /**
  63676. * Get the world position of a point that is in the local space of the bone.
  63677. * @param position The local position
  63678. * @param mesh The mesh that this bone is attached to.
  63679. * @returns The world position
  63680. */
  63681. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63682. if (mesh === void 0) { mesh = null; }
  63683. var result = BABYLON.Vector3.Zero();
  63684. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63685. return result;
  63686. };
  63687. /**
  63688. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63689. * @param position The local position
  63690. * @param mesh The mesh that this bone is attached to.
  63691. * @param result The vector3 that the world position should be copied to.
  63692. */
  63693. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63694. if (mesh === void 0) { mesh = null; }
  63695. var wm = null;
  63696. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63697. if (mesh) {
  63698. wm = mesh.getWorldMatrix();
  63699. }
  63700. this._skeleton.computeAbsoluteTransforms();
  63701. var tmat = Bone._tmpMats[0];
  63702. if (mesh && wm) {
  63703. tmat.copyFrom(this.getAbsoluteTransform());
  63704. tmat.multiplyToRef(wm, tmat);
  63705. }
  63706. else {
  63707. tmat = this.getAbsoluteTransform();
  63708. }
  63709. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63710. };
  63711. /**
  63712. * Get the local position of a point that is in world space.
  63713. * @param position The world position
  63714. * @param mesh The mesh that this bone is attached to.
  63715. * @returns The local position
  63716. */
  63717. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  63718. if (mesh === void 0) { mesh = null; }
  63719. var result = BABYLON.Vector3.Zero();
  63720. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  63721. return result;
  63722. };
  63723. /**
  63724. * Get the local position of a point that is in world space and copy it to the result param.
  63725. * @param position The world position
  63726. * @param mesh The mesh that this bone is attached to.
  63727. * @param result The vector3 that the local position should be copied to.
  63728. */
  63729. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  63730. if (mesh === void 0) { mesh = null; }
  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. tmat.copyFrom(this.getAbsoluteTransform());
  63739. if (mesh && wm) {
  63740. tmat.multiplyToRef(wm, tmat);
  63741. }
  63742. tmat.invert();
  63743. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63744. };
  63745. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63746. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  63747. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63748. return Bone;
  63749. }(BABYLON.Node));
  63750. BABYLON.Bone = Bone;
  63751. })(BABYLON || (BABYLON = {}));
  63752. //# sourceMappingURL=babylon.bone.js.map
  63753. var BABYLON;
  63754. (function (BABYLON) {
  63755. var BoneIKController = /** @class */ (function () {
  63756. function BoneIKController(mesh, bone, options) {
  63757. this.targetPosition = BABYLON.Vector3.Zero();
  63758. this.poleTargetPosition = BABYLON.Vector3.Zero();
  63759. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  63760. this.poleAngle = 0;
  63761. this.slerpAmount = 1;
  63762. this._bone1Quat = BABYLON.Quaternion.Identity();
  63763. this._bone1Mat = BABYLON.Matrix.Identity();
  63764. this._bone2Ang = Math.PI;
  63765. this._maxAngle = Math.PI;
  63766. this._rightHandedSystem = false;
  63767. this._bendAxis = BABYLON.Vector3.Right();
  63768. this._slerping = false;
  63769. this._adjustRoll = 0;
  63770. this._bone2 = bone;
  63771. this._bone1 = bone.getParent();
  63772. if (!this._bone1) {
  63773. return;
  63774. }
  63775. this.mesh = mesh;
  63776. var bonePos = bone.getPosition();
  63777. if (bone.getAbsoluteTransform().determinant() > 0) {
  63778. this._rightHandedSystem = true;
  63779. this._bendAxis.x = 0;
  63780. this._bendAxis.y = 0;
  63781. this._bendAxis.z = -1;
  63782. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  63783. this._adjustRoll = Math.PI * .5;
  63784. this._bendAxis.z = 1;
  63785. }
  63786. }
  63787. if (this._bone1.length) {
  63788. var boneScale1 = this._bone1.getScale();
  63789. var boneScale2 = this._bone2.getScale();
  63790. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  63791. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  63792. }
  63793. else if (this._bone1.children[0]) {
  63794. mesh.computeWorldMatrix(true);
  63795. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  63796. var pos2 = this._bone2.getAbsolutePosition(mesh);
  63797. var pos3 = this._bone1.getAbsolutePosition(mesh);
  63798. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  63799. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  63800. }
  63801. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  63802. this.maxAngle = Math.PI;
  63803. if (options) {
  63804. if (options.targetMesh) {
  63805. this.targetMesh = options.targetMesh;
  63806. this.targetMesh.computeWorldMatrix(true);
  63807. }
  63808. if (options.poleTargetMesh) {
  63809. this.poleTargetMesh = options.poleTargetMesh;
  63810. this.poleTargetMesh.computeWorldMatrix(true);
  63811. }
  63812. else if (options.poleTargetBone) {
  63813. this.poleTargetBone = options.poleTargetBone;
  63814. }
  63815. else if (this._bone1.getParent()) {
  63816. this.poleTargetBone = this._bone1.getParent();
  63817. }
  63818. if (options.poleTargetLocalOffset) {
  63819. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  63820. }
  63821. if (options.poleAngle) {
  63822. this.poleAngle = options.poleAngle;
  63823. }
  63824. if (options.bendAxis) {
  63825. this._bendAxis.copyFrom(options.bendAxis);
  63826. }
  63827. if (options.maxAngle) {
  63828. this.maxAngle = options.maxAngle;
  63829. }
  63830. if (options.slerpAmount) {
  63831. this.slerpAmount = options.slerpAmount;
  63832. }
  63833. }
  63834. }
  63835. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  63836. get: function () {
  63837. return this._maxAngle;
  63838. },
  63839. set: function (value) {
  63840. this._setMaxAngle(value);
  63841. },
  63842. enumerable: true,
  63843. configurable: true
  63844. });
  63845. BoneIKController.prototype._setMaxAngle = function (ang) {
  63846. if (ang < 0) {
  63847. ang = 0;
  63848. }
  63849. if (ang > Math.PI || ang == undefined) {
  63850. ang = Math.PI;
  63851. }
  63852. this._maxAngle = ang;
  63853. var a = this._bone1Length;
  63854. var b = this._bone2Length;
  63855. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  63856. };
  63857. BoneIKController.prototype.update = function () {
  63858. var bone1 = this._bone1;
  63859. if (!bone1) {
  63860. return;
  63861. }
  63862. var target = this.targetPosition;
  63863. var poleTarget = this.poleTargetPosition;
  63864. var mat1 = BoneIKController._tmpMats[0];
  63865. var mat2 = BoneIKController._tmpMats[1];
  63866. if (this.targetMesh) {
  63867. target.copyFrom(this.targetMesh.getAbsolutePosition());
  63868. }
  63869. if (this.poleTargetBone) {
  63870. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  63871. }
  63872. else if (this.poleTargetMesh) {
  63873. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  63874. }
  63875. var bonePos = BoneIKController._tmpVecs[0];
  63876. var zaxis = BoneIKController._tmpVecs[1];
  63877. var xaxis = BoneIKController._tmpVecs[2];
  63878. var yaxis = BoneIKController._tmpVecs[3];
  63879. var upAxis = BoneIKController._tmpVecs[4];
  63880. var _tmpQuat = BoneIKController._tmpQuat;
  63881. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  63882. poleTarget.subtractToRef(bonePos, upAxis);
  63883. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  63884. upAxis.y = 1;
  63885. }
  63886. else {
  63887. upAxis.normalize();
  63888. }
  63889. target.subtractToRef(bonePos, yaxis);
  63890. yaxis.normalize();
  63891. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  63892. zaxis.normalize();
  63893. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  63894. xaxis.normalize();
  63895. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  63896. var a = this._bone1Length;
  63897. var b = this._bone2Length;
  63898. var c = BABYLON.Vector3.Distance(bonePos, target);
  63899. if (this._maxReach > 0) {
  63900. c = Math.min(this._maxReach, c);
  63901. }
  63902. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  63903. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  63904. if (acosa > 1) {
  63905. acosa = 1;
  63906. }
  63907. if (acosb > 1) {
  63908. acosb = 1;
  63909. }
  63910. if (acosa < -1) {
  63911. acosa = -1;
  63912. }
  63913. if (acosb < -1) {
  63914. acosb = -1;
  63915. }
  63916. var angA = Math.acos(acosa);
  63917. var angB = Math.acos(acosb);
  63918. var angC = -angA - angB;
  63919. if (this._rightHandedSystem) {
  63920. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  63921. mat2.multiplyToRef(mat1, mat1);
  63922. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  63923. mat2.multiplyToRef(mat1, mat1);
  63924. }
  63925. else {
  63926. var _tmpVec = BoneIKController._tmpVecs[5];
  63927. _tmpVec.copyFrom(this._bendAxis);
  63928. _tmpVec.x *= -1;
  63929. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  63930. mat2.multiplyToRef(mat1, mat1);
  63931. }
  63932. if (this.poleAngle) {
  63933. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  63934. mat1.multiplyToRef(mat2, mat1);
  63935. }
  63936. if (this._bone1) {
  63937. if (this.slerpAmount < 1) {
  63938. if (!this._slerping) {
  63939. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  63940. }
  63941. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  63942. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  63943. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  63944. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  63945. this._slerping = true;
  63946. }
  63947. else {
  63948. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  63949. this._bone1Mat.copyFrom(mat1);
  63950. this._slerping = false;
  63951. }
  63952. }
  63953. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  63954. this._bone2Ang = angC;
  63955. };
  63956. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63957. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  63958. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63959. return BoneIKController;
  63960. }());
  63961. BABYLON.BoneIKController = BoneIKController;
  63962. })(BABYLON || (BABYLON = {}));
  63963. //# sourceMappingURL=babylon.boneIKController.js.map
  63964. var BABYLON;
  63965. (function (BABYLON) {
  63966. var BoneLookController = /** @class */ (function () {
  63967. /**
  63968. * Create a BoneLookController
  63969. * @param mesh the mesh that the bone belongs to
  63970. * @param bone the bone that will be looking to the target
  63971. * @param target the target Vector3 to look at
  63972. * @param settings optional settings:
  63973. * - maxYaw: the maximum angle the bone will yaw to
  63974. * - minYaw: the minimum angle the bone will yaw to
  63975. * - maxPitch: the maximum angle the bone will pitch to
  63976. * - minPitch: the minimum angle the bone will yaw to
  63977. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  63978. * - upAxis: the up axis of the coordinate system
  63979. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63980. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  63981. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  63982. * - adjustYaw: used to make an adjustment to the yaw of the bone
  63983. * - adjustPitch: used to make an adjustment to the pitch of the bone
  63984. * - adjustRoll: used to make an adjustment to the roll of the bone
  63985. **/
  63986. function BoneLookController(mesh, bone, target, options) {
  63987. /**
  63988. * The up axis of the coordinate system that is used when the bone is rotated.
  63989. */
  63990. this.upAxis = BABYLON.Vector3.Up();
  63991. /**
  63992. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63993. */
  63994. this.upAxisSpace = BABYLON.Space.LOCAL;
  63995. /**
  63996. * Used to make an adjustment to the yaw of the bone.
  63997. */
  63998. this.adjustYaw = 0;
  63999. /**
  64000. * Used to make an adjustment to the pitch of the bone.
  64001. */
  64002. this.adjustPitch = 0;
  64003. /**
  64004. * Used to make an adjustment to the roll of the bone.
  64005. */
  64006. this.adjustRoll = 0;
  64007. /**
  64008. * 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).
  64009. */
  64010. this.slerpAmount = 1;
  64011. this._boneQuat = BABYLON.Quaternion.Identity();
  64012. this._slerping = false;
  64013. this._firstFrameSkipped = false;
  64014. this._fowardAxis = BABYLON.Vector3.Forward();
  64015. this.mesh = mesh;
  64016. this.bone = bone;
  64017. this.target = target;
  64018. if (options) {
  64019. if (options.adjustYaw) {
  64020. this.adjustYaw = options.adjustYaw;
  64021. }
  64022. if (options.adjustPitch) {
  64023. this.adjustPitch = options.adjustPitch;
  64024. }
  64025. if (options.adjustRoll) {
  64026. this.adjustRoll = options.adjustRoll;
  64027. }
  64028. if (options.maxYaw != null) {
  64029. this.maxYaw = options.maxYaw;
  64030. }
  64031. else {
  64032. this.maxYaw = Math.PI;
  64033. }
  64034. if (options.minYaw != null) {
  64035. this.minYaw = options.minYaw;
  64036. }
  64037. else {
  64038. this.minYaw = -Math.PI;
  64039. }
  64040. if (options.maxPitch != null) {
  64041. this.maxPitch = options.maxPitch;
  64042. }
  64043. else {
  64044. this.maxPitch = Math.PI;
  64045. }
  64046. if (options.minPitch != null) {
  64047. this.minPitch = options.minPitch;
  64048. }
  64049. else {
  64050. this.minPitch = -Math.PI;
  64051. }
  64052. if (options.slerpAmount != null) {
  64053. this.slerpAmount = options.slerpAmount;
  64054. }
  64055. if (options.upAxis != null) {
  64056. this.upAxis = options.upAxis;
  64057. }
  64058. if (options.upAxisSpace != null) {
  64059. this.upAxisSpace = options.upAxisSpace;
  64060. }
  64061. if (options.yawAxis != null || options.pitchAxis != null) {
  64062. var newYawAxis = BABYLON.Axis.Y;
  64063. var newPitchAxis = BABYLON.Axis.X;
  64064. if (options.yawAxis != null) {
  64065. newYawAxis = options.yawAxis.clone();
  64066. newYawAxis.normalize();
  64067. }
  64068. if (options.pitchAxis != null) {
  64069. newPitchAxis = options.pitchAxis.clone();
  64070. newPitchAxis.normalize();
  64071. }
  64072. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64073. this._transformYawPitch = BABYLON.Matrix.Identity();
  64074. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64075. this._transformYawPitchInv = this._transformYawPitch.clone();
  64076. this._transformYawPitch.invert();
  64077. }
  64078. }
  64079. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64080. this.upAxisSpace = BABYLON.Space.LOCAL;
  64081. }
  64082. }
  64083. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64084. /**
  64085. * Get/set the minimum yaw angle that the bone can look to.
  64086. */
  64087. get: function () {
  64088. return this._minYaw;
  64089. },
  64090. set: function (value) {
  64091. this._minYaw = value;
  64092. this._minYawSin = Math.sin(value);
  64093. this._minYawCos = Math.cos(value);
  64094. if (this._maxYaw != null) {
  64095. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64096. this._yawRange = this._maxYaw - this._minYaw;
  64097. }
  64098. },
  64099. enumerable: true,
  64100. configurable: true
  64101. });
  64102. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64103. /**
  64104. * Get/set the maximum yaw angle that the bone can look to.
  64105. */
  64106. get: function () {
  64107. return this._maxYaw;
  64108. },
  64109. set: function (value) {
  64110. this._maxYaw = value;
  64111. this._maxYawSin = Math.sin(value);
  64112. this._maxYawCos = Math.cos(value);
  64113. if (this._minYaw != null) {
  64114. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64115. this._yawRange = this._maxYaw - this._minYaw;
  64116. }
  64117. },
  64118. enumerable: true,
  64119. configurable: true
  64120. });
  64121. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64122. /**
  64123. * Get/set the minimum pitch angle that the bone can look to.
  64124. */
  64125. get: function () {
  64126. return this._minPitch;
  64127. },
  64128. set: function (value) {
  64129. this._minPitch = value;
  64130. this._minPitchTan = Math.tan(value);
  64131. },
  64132. enumerable: true,
  64133. configurable: true
  64134. });
  64135. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64136. /**
  64137. * Get/set the maximum pitch angle that the bone can look to.
  64138. */
  64139. get: function () {
  64140. return this._maxPitch;
  64141. },
  64142. set: function (value) {
  64143. this._maxPitch = value;
  64144. this._maxPitchTan = Math.tan(value);
  64145. },
  64146. enumerable: true,
  64147. configurable: true
  64148. });
  64149. /**
  64150. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64151. */
  64152. BoneLookController.prototype.update = function () {
  64153. //skip the first frame when slerping so that the mesh rotation is correct
  64154. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64155. this._firstFrameSkipped = true;
  64156. return;
  64157. }
  64158. var bone = this.bone;
  64159. var bonePos = BoneLookController._tmpVecs[0];
  64160. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64161. var target = this.target;
  64162. var _tmpMat1 = BoneLookController._tmpMats[0];
  64163. var _tmpMat2 = BoneLookController._tmpMats[1];
  64164. var mesh = this.mesh;
  64165. var parentBone = bone.getParent();
  64166. var upAxis = BoneLookController._tmpVecs[1];
  64167. upAxis.copyFrom(this.upAxis);
  64168. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64169. if (this._transformYawPitch) {
  64170. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64171. }
  64172. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64173. }
  64174. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64175. mesh.getDirectionToRef(upAxis, upAxis);
  64176. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64177. upAxis.normalize();
  64178. }
  64179. }
  64180. var checkYaw = false;
  64181. var checkPitch = false;
  64182. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64183. checkYaw = true;
  64184. }
  64185. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64186. checkPitch = true;
  64187. }
  64188. if (checkYaw || checkPitch) {
  64189. var spaceMat = BoneLookController._tmpMats[2];
  64190. var spaceMatInv = BoneLookController._tmpMats[3];
  64191. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64192. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64193. }
  64194. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64195. spaceMat.copyFrom(mesh.getWorldMatrix());
  64196. }
  64197. else {
  64198. var forwardAxis = BoneLookController._tmpVecs[2];
  64199. forwardAxis.copyFrom(this._fowardAxis);
  64200. if (this._transformYawPitch) {
  64201. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64202. }
  64203. if (parentBone) {
  64204. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64205. }
  64206. else {
  64207. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64208. }
  64209. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64210. rightAxis.normalize();
  64211. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64212. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64213. }
  64214. spaceMat.invertToRef(spaceMatInv);
  64215. var xzlen = null;
  64216. if (checkPitch) {
  64217. var localTarget = BoneLookController._tmpVecs[3];
  64218. target.subtractToRef(bonePos, localTarget);
  64219. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64220. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64221. var pitch = Math.atan2(localTarget.y, xzlen);
  64222. var newPitch = pitch;
  64223. if (pitch > this._maxPitch) {
  64224. localTarget.y = this._maxPitchTan * xzlen;
  64225. newPitch = this._maxPitch;
  64226. }
  64227. else if (pitch < this._minPitch) {
  64228. localTarget.y = this._minPitchTan * xzlen;
  64229. newPitch = this._minPitch;
  64230. }
  64231. if (pitch != newPitch) {
  64232. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64233. localTarget.addInPlace(bonePos);
  64234. target = localTarget;
  64235. }
  64236. }
  64237. if (checkYaw) {
  64238. var localTarget = BoneLookController._tmpVecs[4];
  64239. target.subtractToRef(bonePos, localTarget);
  64240. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64241. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64242. var newYaw = yaw;
  64243. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64244. if (xzlen == null) {
  64245. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64246. }
  64247. if (this._yawRange > Math.PI) {
  64248. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64249. localTarget.z = this._maxYawCos * xzlen;
  64250. localTarget.x = this._maxYawSin * xzlen;
  64251. newYaw = this._maxYaw;
  64252. }
  64253. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64254. localTarget.z = this._minYawCos * xzlen;
  64255. localTarget.x = this._minYawSin * xzlen;
  64256. newYaw = this._minYaw;
  64257. }
  64258. }
  64259. else {
  64260. if (yaw > this._maxYaw) {
  64261. localTarget.z = this._maxYawCos * xzlen;
  64262. localTarget.x = this._maxYawSin * xzlen;
  64263. newYaw = this._maxYaw;
  64264. }
  64265. else if (yaw < this._minYaw) {
  64266. localTarget.z = this._minYawCos * xzlen;
  64267. localTarget.x = this._minYawSin * xzlen;
  64268. newYaw = this._minYaw;
  64269. }
  64270. }
  64271. }
  64272. if (this._slerping && this._yawRange > Math.PI) {
  64273. //are we going to be crossing into the min/max region?
  64274. var boneFwd = BoneLookController._tmpVecs[8];
  64275. boneFwd.copyFrom(BABYLON.Axis.Z);
  64276. if (this._transformYawPitch) {
  64277. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64278. }
  64279. var boneRotMat = BoneLookController._tmpMats[4];
  64280. this._boneQuat.toRotationMatrix(boneRotMat);
  64281. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64282. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64283. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64284. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64285. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64286. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64287. if (angBtwTar > angBtwMidYaw) {
  64288. if (xzlen == null) {
  64289. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64290. }
  64291. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64292. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64293. if (angBtwMin < angBtwMax) {
  64294. newYaw = boneYaw + Math.PI * .75;
  64295. localTarget.z = Math.cos(newYaw) * xzlen;
  64296. localTarget.x = Math.sin(newYaw) * xzlen;
  64297. }
  64298. else {
  64299. newYaw = boneYaw - Math.PI * .75;
  64300. localTarget.z = Math.cos(newYaw) * xzlen;
  64301. localTarget.x = Math.sin(newYaw) * xzlen;
  64302. }
  64303. }
  64304. }
  64305. if (yaw != newYaw) {
  64306. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64307. localTarget.addInPlace(bonePos);
  64308. target = localTarget;
  64309. }
  64310. }
  64311. }
  64312. var zaxis = BoneLookController._tmpVecs[5];
  64313. var xaxis = BoneLookController._tmpVecs[6];
  64314. var yaxis = BoneLookController._tmpVecs[7];
  64315. var _tmpQuat = BoneLookController._tmpQuat;
  64316. target.subtractToRef(bonePos, zaxis);
  64317. zaxis.normalize();
  64318. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64319. xaxis.normalize();
  64320. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64321. yaxis.normalize();
  64322. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64323. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64324. return;
  64325. }
  64326. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64327. return;
  64328. }
  64329. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64330. return;
  64331. }
  64332. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64333. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64334. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64335. }
  64336. if (this.slerpAmount < 1) {
  64337. if (!this._slerping) {
  64338. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64339. }
  64340. if (this._transformYawPitch) {
  64341. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64342. }
  64343. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64344. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64345. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64346. this._slerping = true;
  64347. }
  64348. else {
  64349. if (this._transformYawPitch) {
  64350. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64351. }
  64352. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64353. this._slerping = false;
  64354. }
  64355. };
  64356. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64357. var angDiff = ang2 - ang1;
  64358. angDiff %= Math.PI * 2;
  64359. if (angDiff > Math.PI) {
  64360. angDiff -= Math.PI * 2;
  64361. }
  64362. else if (angDiff < -Math.PI) {
  64363. angDiff += Math.PI * 2;
  64364. }
  64365. return angDiff;
  64366. };
  64367. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64368. ang1 %= (2 * Math.PI);
  64369. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64370. ang2 %= (2 * Math.PI);
  64371. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64372. var ab = 0;
  64373. if (ang1 < ang2) {
  64374. ab = ang2 - ang1;
  64375. }
  64376. else {
  64377. ab = ang1 - ang2;
  64378. }
  64379. if (ab > Math.PI) {
  64380. ab = Math.PI * 2 - ab;
  64381. }
  64382. return ab;
  64383. };
  64384. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64385. ang %= (2 * Math.PI);
  64386. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64387. ang1 %= (2 * Math.PI);
  64388. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64389. ang2 %= (2 * Math.PI);
  64390. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64391. if (ang1 < ang2) {
  64392. if (ang > ang1 && ang < ang2) {
  64393. return true;
  64394. }
  64395. }
  64396. else {
  64397. if (ang > ang2 && ang < ang1) {
  64398. return true;
  64399. }
  64400. }
  64401. return false;
  64402. };
  64403. 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()];
  64404. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64405. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64406. return BoneLookController;
  64407. }());
  64408. BABYLON.BoneLookController = BoneLookController;
  64409. })(BABYLON || (BABYLON = {}));
  64410. //# sourceMappingURL=babylon.boneLookController.js.map
  64411. var BABYLON;
  64412. (function (BABYLON) {
  64413. var Skeleton = /** @class */ (function () {
  64414. function Skeleton(name, id, scene) {
  64415. this.name = name;
  64416. this.id = id;
  64417. this.bones = new Array();
  64418. this.needInitialSkinMatrix = false;
  64419. this._isDirty = true;
  64420. this._meshesWithPoseMatrix = new Array();
  64421. this._identity = BABYLON.Matrix.Identity();
  64422. this._ranges = {};
  64423. this._lastAbsoluteTransformsUpdateId = -1;
  64424. // Events
  64425. /**
  64426. * An event triggered before computing the skeleton's matrices
  64427. * @type {BABYLON.Observable}
  64428. */
  64429. this.onBeforeComputeObservable = new BABYLON.Observable();
  64430. this.bones = [];
  64431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64432. scene.skeletons.push(this);
  64433. //make sure it will recalculate the matrix next time prepare is called.
  64434. this._isDirty = true;
  64435. }
  64436. // Members
  64437. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64438. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64439. return mesh._bonesTransformMatrices;
  64440. }
  64441. if (!this._transformMatrices) {
  64442. this.prepare();
  64443. }
  64444. return this._transformMatrices;
  64445. };
  64446. Skeleton.prototype.getScene = function () {
  64447. return this._scene;
  64448. };
  64449. // Methods
  64450. /**
  64451. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64452. */
  64453. Skeleton.prototype.toString = function (fullDetails) {
  64454. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64455. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64456. if (fullDetails) {
  64457. ret += ", Ranges: {";
  64458. var first = true;
  64459. for (var name_1 in this._ranges) {
  64460. if (first) {
  64461. ret += ", ";
  64462. first = false;
  64463. }
  64464. ret += name_1;
  64465. }
  64466. ret += "}";
  64467. }
  64468. return ret;
  64469. };
  64470. /**
  64471. * Get bone's index searching by name
  64472. * @param {string} name is bone's name to search for
  64473. * @return {number} Indice of the bone. Returns -1 if not found
  64474. */
  64475. Skeleton.prototype.getBoneIndexByName = function (name) {
  64476. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64477. if (this.bones[boneIndex].name === name) {
  64478. return boneIndex;
  64479. }
  64480. }
  64481. return -1;
  64482. };
  64483. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64484. // check name not already in use
  64485. if (!this._ranges[name]) {
  64486. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64487. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64488. if (this.bones[i].animations[0]) {
  64489. this.bones[i].animations[0].createRange(name, from, to);
  64490. }
  64491. }
  64492. }
  64493. };
  64494. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64495. if (deleteFrames === void 0) { deleteFrames = true; }
  64496. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64497. if (this.bones[i].animations[0]) {
  64498. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64499. }
  64500. }
  64501. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64502. };
  64503. Skeleton.prototype.getAnimationRange = function (name) {
  64504. return this._ranges[name];
  64505. };
  64506. /**
  64507. * Returns as an Array, all AnimationRanges defined on this skeleton
  64508. */
  64509. Skeleton.prototype.getAnimationRanges = function () {
  64510. var animationRanges = [];
  64511. var name;
  64512. var i = 0;
  64513. for (name in this._ranges) {
  64514. animationRanges[i] = this._ranges[name];
  64515. i++;
  64516. }
  64517. return animationRanges;
  64518. };
  64519. /**
  64520. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64521. */
  64522. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64523. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64524. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64525. return false;
  64526. }
  64527. var ret = true;
  64528. var frameOffset = this._getHighestAnimationFrame() + 1;
  64529. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64530. var boneDict = {};
  64531. var sourceBones = source.bones;
  64532. var nBones;
  64533. var i;
  64534. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64535. boneDict[sourceBones[i].name] = sourceBones[i];
  64536. }
  64537. if (this.bones.length !== sourceBones.length) {
  64538. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64539. ret = false;
  64540. }
  64541. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64542. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64543. var boneName = this.bones[i].name;
  64544. var sourceBone = boneDict[boneName];
  64545. if (sourceBone) {
  64546. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64547. }
  64548. else {
  64549. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64550. ret = false;
  64551. }
  64552. }
  64553. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64554. var range = source.getAnimationRange(name);
  64555. if (range) {
  64556. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64557. }
  64558. return ret;
  64559. };
  64560. Skeleton.prototype.returnToRest = function () {
  64561. for (var index = 0; index < this.bones.length; index++) {
  64562. this.bones[index].returnToRest();
  64563. }
  64564. };
  64565. Skeleton.prototype._getHighestAnimationFrame = function () {
  64566. var ret = 0;
  64567. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64568. if (this.bones[i].animations[0]) {
  64569. var highest = this.bones[i].animations[0].getHighestFrame();
  64570. if (ret < highest) {
  64571. ret = highest;
  64572. }
  64573. }
  64574. }
  64575. return ret;
  64576. };
  64577. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64578. var range = this.getAnimationRange(name);
  64579. if (!range) {
  64580. return null;
  64581. }
  64582. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64583. };
  64584. Skeleton.prototype._markAsDirty = function () {
  64585. this._isDirty = true;
  64586. };
  64587. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64588. this._meshesWithPoseMatrix.push(mesh);
  64589. };
  64590. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64591. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64592. if (index > -1) {
  64593. this._meshesWithPoseMatrix.splice(index, 1);
  64594. }
  64595. };
  64596. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64597. this.onBeforeComputeObservable.notifyObservers(this);
  64598. for (var index = 0; index < this.bones.length; index++) {
  64599. var bone = this.bones[index];
  64600. var parentBone = bone.getParent();
  64601. if (parentBone) {
  64602. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64603. }
  64604. else {
  64605. if (initialSkinMatrix) {
  64606. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64607. }
  64608. else {
  64609. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64610. }
  64611. }
  64612. if (bone._index !== -1) {
  64613. var mappedIndex = bone._index === null ? index : bone._index;
  64614. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64615. }
  64616. }
  64617. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64618. };
  64619. Skeleton.prototype.prepare = function () {
  64620. if (!this._isDirty) {
  64621. return;
  64622. }
  64623. if (this.needInitialSkinMatrix) {
  64624. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64625. var mesh = this._meshesWithPoseMatrix[index];
  64626. var poseMatrix = mesh.getPoseMatrix();
  64627. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64628. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64629. }
  64630. if (this._synchronizedWithMesh !== mesh) {
  64631. this._synchronizedWithMesh = mesh;
  64632. // Prepare bones
  64633. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64634. var bone = this.bones[boneIndex];
  64635. if (!bone.getParent()) {
  64636. var matrix = bone.getBaseMatrix();
  64637. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64638. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64639. }
  64640. }
  64641. }
  64642. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64643. }
  64644. }
  64645. else {
  64646. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64647. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64648. }
  64649. this._computeTransformMatrices(this._transformMatrices, null);
  64650. }
  64651. this._isDirty = false;
  64652. this._scene._activeBones.addCount(this.bones.length, false);
  64653. };
  64654. Skeleton.prototype.getAnimatables = function () {
  64655. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64656. this._animatables = [];
  64657. for (var index = 0; index < this.bones.length; index++) {
  64658. this._animatables.push(this.bones[index]);
  64659. }
  64660. }
  64661. return this._animatables;
  64662. };
  64663. Skeleton.prototype.clone = function (name, id) {
  64664. var result = new Skeleton(name, id || name, this._scene);
  64665. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64666. for (var index = 0; index < this.bones.length; index++) {
  64667. var source = this.bones[index];
  64668. var parentBone = null;
  64669. var parent_1 = source.getParent();
  64670. if (parent_1) {
  64671. var parentIndex = this.bones.indexOf(parent_1);
  64672. parentBone = result.bones[parentIndex];
  64673. }
  64674. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64675. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64676. }
  64677. if (this._ranges) {
  64678. result._ranges = {};
  64679. for (var rangeName in this._ranges) {
  64680. var range = this._ranges[rangeName];
  64681. if (range) {
  64682. result._ranges[rangeName] = range.clone();
  64683. }
  64684. }
  64685. }
  64686. this._isDirty = true;
  64687. return result;
  64688. };
  64689. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64690. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64691. this.bones.forEach(function (bone) {
  64692. bone.animations.forEach(function (animation) {
  64693. animation.enableBlending = true;
  64694. animation.blendingSpeed = blendingSpeed;
  64695. });
  64696. });
  64697. };
  64698. Skeleton.prototype.dispose = function () {
  64699. this._meshesWithPoseMatrix = [];
  64700. // Animations
  64701. this.getScene().stopAnimation(this);
  64702. // Remove from scene
  64703. this.getScene().removeSkeleton(this);
  64704. };
  64705. Skeleton.prototype.serialize = function () {
  64706. var serializationObject = {};
  64707. serializationObject.name = this.name;
  64708. serializationObject.id = this.id;
  64709. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  64710. serializationObject.bones = [];
  64711. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64712. for (var index = 0; index < this.bones.length; index++) {
  64713. var bone = this.bones[index];
  64714. var parent_2 = bone.getParent();
  64715. var serializedBone = {
  64716. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  64717. name: bone.name,
  64718. matrix: bone.getBaseMatrix().toArray(),
  64719. rest: bone.getRestPose().toArray()
  64720. };
  64721. serializationObject.bones.push(serializedBone);
  64722. if (bone.length) {
  64723. serializedBone.length = bone.length;
  64724. }
  64725. if (bone.animations && bone.animations.length > 0) {
  64726. serializedBone.animation = bone.animations[0].serialize();
  64727. }
  64728. serializationObject.ranges = [];
  64729. for (var name in this._ranges) {
  64730. var source = this._ranges[name];
  64731. if (!source) {
  64732. continue;
  64733. }
  64734. var range = {};
  64735. range.name = name;
  64736. range.from = source.from;
  64737. range.to = source.to;
  64738. serializationObject.ranges.push(range);
  64739. }
  64740. }
  64741. return serializationObject;
  64742. };
  64743. Skeleton.Parse = function (parsedSkeleton, scene) {
  64744. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  64745. if (parsedSkeleton.dimensionsAtRest) {
  64746. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  64747. }
  64748. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  64749. var index;
  64750. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  64751. var parsedBone = parsedSkeleton.bones[index];
  64752. var parentBone = null;
  64753. if (parsedBone.parentBoneIndex > -1) {
  64754. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  64755. }
  64756. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  64757. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  64758. if (parsedBone.length) {
  64759. bone.length = parsedBone.length;
  64760. }
  64761. if (parsedBone.animation) {
  64762. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  64763. }
  64764. }
  64765. // placed after bones, so createAnimationRange can cascade down
  64766. if (parsedSkeleton.ranges) {
  64767. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  64768. var data = parsedSkeleton.ranges[index];
  64769. skeleton.createAnimationRange(data.name, data.from, data.to);
  64770. }
  64771. }
  64772. return skeleton;
  64773. };
  64774. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  64775. if (forceUpdate === void 0) { forceUpdate = false; }
  64776. var renderId = this._scene.getRenderId();
  64777. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  64778. this.bones[0].computeAbsoluteTransforms();
  64779. this._lastAbsoluteTransformsUpdateId = renderId;
  64780. }
  64781. };
  64782. Skeleton.prototype.getPoseMatrix = function () {
  64783. var poseMatrix = null;
  64784. if (this._meshesWithPoseMatrix.length > 0) {
  64785. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  64786. }
  64787. return poseMatrix;
  64788. };
  64789. Skeleton.prototype.sortBones = function () {
  64790. var bones = new Array();
  64791. var visited = new Array(this.bones.length);
  64792. for (var index = 0; index < this.bones.length; index++) {
  64793. this._sortBones(index, bones, visited);
  64794. }
  64795. this.bones = bones;
  64796. };
  64797. Skeleton.prototype._sortBones = function (index, bones, visited) {
  64798. if (visited[index]) {
  64799. return;
  64800. }
  64801. visited[index] = true;
  64802. var bone = this.bones[index];
  64803. if (bone._index === undefined) {
  64804. bone._index = index;
  64805. }
  64806. var parentBone = bone.getParent();
  64807. if (parentBone) {
  64808. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  64809. }
  64810. bones.push(bone);
  64811. };
  64812. return Skeleton;
  64813. }());
  64814. BABYLON.Skeleton = Skeleton;
  64815. })(BABYLON || (BABYLON = {}));
  64816. //# sourceMappingURL=babylon.skeleton.js.map
  64817. var BABYLON;
  64818. (function (BABYLON) {
  64819. var SphericalPolynomial = /** @class */ (function () {
  64820. function SphericalPolynomial() {
  64821. this.x = BABYLON.Vector3.Zero();
  64822. this.y = BABYLON.Vector3.Zero();
  64823. this.z = BABYLON.Vector3.Zero();
  64824. this.xx = BABYLON.Vector3.Zero();
  64825. this.yy = BABYLON.Vector3.Zero();
  64826. this.zz = BABYLON.Vector3.Zero();
  64827. this.xy = BABYLON.Vector3.Zero();
  64828. this.yz = BABYLON.Vector3.Zero();
  64829. this.zx = BABYLON.Vector3.Zero();
  64830. }
  64831. SphericalPolynomial.prototype.addAmbient = function (color) {
  64832. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64833. this.xx = this.xx.add(colorVector);
  64834. this.yy = this.yy.add(colorVector);
  64835. this.zz = this.zz.add(colorVector);
  64836. };
  64837. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  64838. var result = new SphericalPolynomial();
  64839. result.x = harmonics.L11.scale(1.02333);
  64840. result.y = harmonics.L1_1.scale(1.02333);
  64841. result.z = harmonics.L10.scale(1.02333);
  64842. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  64843. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  64844. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  64845. result.yz = harmonics.L2_1.scale(0.858086);
  64846. result.zx = harmonics.L21.scale(0.858086);
  64847. result.xy = harmonics.L2_2.scale(0.858086);
  64848. result.scale(1.0 / Math.PI);
  64849. return result;
  64850. };
  64851. SphericalPolynomial.prototype.scale = function (scale) {
  64852. this.x = this.x.scale(scale);
  64853. this.y = this.y.scale(scale);
  64854. this.z = this.z.scale(scale);
  64855. this.xx = this.xx.scale(scale);
  64856. this.yy = this.yy.scale(scale);
  64857. this.zz = this.zz.scale(scale);
  64858. this.yz = this.yz.scale(scale);
  64859. this.zx = this.zx.scale(scale);
  64860. this.xy = this.xy.scale(scale);
  64861. };
  64862. return SphericalPolynomial;
  64863. }());
  64864. BABYLON.SphericalPolynomial = SphericalPolynomial;
  64865. var SphericalHarmonics = /** @class */ (function () {
  64866. function SphericalHarmonics() {
  64867. this.L00 = BABYLON.Vector3.Zero();
  64868. this.L1_1 = BABYLON.Vector3.Zero();
  64869. this.L10 = BABYLON.Vector3.Zero();
  64870. this.L11 = BABYLON.Vector3.Zero();
  64871. this.L2_2 = BABYLON.Vector3.Zero();
  64872. this.L2_1 = BABYLON.Vector3.Zero();
  64873. this.L20 = BABYLON.Vector3.Zero();
  64874. this.L21 = BABYLON.Vector3.Zero();
  64875. this.L22 = BABYLON.Vector3.Zero();
  64876. }
  64877. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  64878. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64879. var c = colorVector.scale(deltaSolidAngle);
  64880. this.L00 = this.L00.add(c.scale(0.282095));
  64881. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  64882. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  64883. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  64884. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  64885. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  64886. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  64887. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  64888. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  64889. };
  64890. SphericalHarmonics.prototype.scale = function (scale) {
  64891. this.L00 = this.L00.scale(scale);
  64892. this.L1_1 = this.L1_1.scale(scale);
  64893. this.L10 = this.L10.scale(scale);
  64894. this.L11 = this.L11.scale(scale);
  64895. this.L2_2 = this.L2_2.scale(scale);
  64896. this.L2_1 = this.L2_1.scale(scale);
  64897. this.L20 = this.L20.scale(scale);
  64898. this.L21 = this.L21.scale(scale);
  64899. this.L22 = this.L22.scale(scale);
  64900. };
  64901. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  64902. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  64903. //
  64904. // E_lm = A_l * L_lm
  64905. //
  64906. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  64907. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  64908. // the scaling factors are given in equation 9.
  64909. // Constant (Band 0)
  64910. this.L00 = this.L00.scale(3.141593);
  64911. // Linear (Band 1)
  64912. this.L1_1 = this.L1_1.scale(2.094395);
  64913. this.L10 = this.L10.scale(2.094395);
  64914. this.L11 = this.L11.scale(2.094395);
  64915. // Quadratic (Band 2)
  64916. this.L2_2 = this.L2_2.scale(0.785398);
  64917. this.L2_1 = this.L2_1.scale(0.785398);
  64918. this.L20 = this.L20.scale(0.785398);
  64919. this.L21 = this.L21.scale(0.785398);
  64920. this.L22 = this.L22.scale(0.785398);
  64921. };
  64922. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  64923. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  64924. // L = (1/pi) * E * rho
  64925. //
  64926. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  64927. this.scale(1.0 / Math.PI);
  64928. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  64929. // (The pixel shader must apply albedo after texture fetches, etc).
  64930. };
  64931. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  64932. var result = new SphericalHarmonics();
  64933. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  64934. result.L1_1 = polynomial.y.scale(0.977204);
  64935. result.L10 = polynomial.z.scale(0.977204);
  64936. result.L11 = polynomial.x.scale(0.977204);
  64937. result.L2_2 = polynomial.xy.scale(1.16538);
  64938. result.L2_1 = polynomial.yz.scale(1.16538);
  64939. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  64940. result.L21 = polynomial.zx.scale(1.16538);
  64941. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  64942. result.scale(Math.PI);
  64943. return result;
  64944. };
  64945. return SphericalHarmonics;
  64946. }());
  64947. BABYLON.SphericalHarmonics = SphericalHarmonics;
  64948. })(BABYLON || (BABYLON = {}));
  64949. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  64950. var BABYLON;
  64951. (function (BABYLON) {
  64952. var FileFaceOrientation = /** @class */ (function () {
  64953. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  64954. this.name = name;
  64955. this.worldAxisForNormal = worldAxisForNormal;
  64956. this.worldAxisForFileX = worldAxisForFileX;
  64957. this.worldAxisForFileY = worldAxisForFileY;
  64958. }
  64959. return FileFaceOrientation;
  64960. }());
  64961. ;
  64962. /**
  64963. * Helper class dealing with the extraction of spherical polynomial dataArray
  64964. * from a cube map.
  64965. */
  64966. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  64967. function CubeMapToSphericalPolynomialTools() {
  64968. }
  64969. /**
  64970. * Converts a texture to the according Spherical Polynomial data.
  64971. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64972. *
  64973. * @param texture The texture to extract the information from.
  64974. * @return The Spherical Polynomial data.
  64975. */
  64976. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  64977. if (!texture.isCube) {
  64978. // Only supports cube Textures currently.
  64979. return null;
  64980. }
  64981. var size = texture.getSize().width;
  64982. var right = texture.readPixels(0);
  64983. var left = texture.readPixels(1);
  64984. var up;
  64985. var down;
  64986. if (texture.isRenderTarget) {
  64987. up = texture.readPixels(3);
  64988. down = texture.readPixels(2);
  64989. }
  64990. else {
  64991. up = texture.readPixels(2);
  64992. down = texture.readPixels(3);
  64993. }
  64994. var front = texture.readPixels(4);
  64995. var back = texture.readPixels(5);
  64996. var gammaSpace = texture.gammaSpace;
  64997. // Always read as RGBA.
  64998. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  64999. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65000. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65001. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65002. }
  65003. var cubeInfo = {
  65004. size: size,
  65005. right: right,
  65006. left: left,
  65007. up: up,
  65008. down: down,
  65009. front: front,
  65010. back: back,
  65011. format: format,
  65012. type: type,
  65013. gammaSpace: gammaSpace,
  65014. };
  65015. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65016. };
  65017. /**
  65018. * Converts a cubemap to the according Spherical Polynomial data.
  65019. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65020. *
  65021. * @param cubeInfo The Cube map to extract the information from.
  65022. * @return The Spherical Polynomial data.
  65023. */
  65024. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65025. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65026. var totalSolidAngle = 0.0;
  65027. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65028. var du = 2.0 / cubeInfo.size;
  65029. var dv = du;
  65030. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65031. var minUV = du * 0.5 - 1.0;
  65032. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65033. var fileFace = this.FileFaces[faceIndex];
  65034. var dataArray = cubeInfo[fileFace.name];
  65035. var v = minUV;
  65036. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65037. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65038. // Because SP is still linear, so summation is fine in that basis.
  65039. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65040. for (var y = 0; y < cubeInfo.size; y++) {
  65041. var u = minUV;
  65042. for (var x = 0; x < cubeInfo.size; x++) {
  65043. // World direction (not normalised)
  65044. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65045. worldDirection.normalize();
  65046. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65047. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65048. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65049. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65050. // Handle Integer types.
  65051. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65052. r /= 255;
  65053. g /= 255;
  65054. b /= 255;
  65055. }
  65056. // Handle Gamma space textures.
  65057. if (cubeInfo.gammaSpace) {
  65058. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65059. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65060. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65061. }
  65062. var color = new BABYLON.Color3(r, g, b);
  65063. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65064. totalSolidAngle += deltaSolidAngle;
  65065. u += du;
  65066. }
  65067. v += dv;
  65068. }
  65069. }
  65070. // Solid angle for entire sphere is 4*pi
  65071. var sphereSolidAngle = 4.0 * Math.PI;
  65072. // Adjust the solid angle to allow for how many faces we processed.
  65073. var facesProcessed = 6.0;
  65074. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65075. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65076. // This is needed because the numerical integration over the cube uses a
  65077. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65078. // and also to compensate for accumulative error due to float precision in the summation.
  65079. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65080. sphericalHarmonics.scale(correctionFactor);
  65081. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65082. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65083. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65084. };
  65085. CubeMapToSphericalPolynomialTools.FileFaces = [
  65086. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65087. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65088. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65089. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65090. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65091. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65092. ];
  65093. return CubeMapToSphericalPolynomialTools;
  65094. }());
  65095. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65096. })(BABYLON || (BABYLON = {}));
  65097. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65098. var BABYLON;
  65099. (function (BABYLON) {
  65100. /**
  65101. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65102. */
  65103. var PanoramaToCubeMapTools = /** @class */ (function () {
  65104. function PanoramaToCubeMapTools() {
  65105. }
  65106. /**
  65107. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65108. *
  65109. * @param float32Array The source data.
  65110. * @param inputWidth The width of the input panorama.
  65111. * @param inputhHeight The height of the input panorama.
  65112. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65113. * @return The cubemap data
  65114. */
  65115. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65116. if (!float32Array) {
  65117. throw "ConvertPanoramaToCubemap: input cannot be null";
  65118. }
  65119. if (float32Array.length != inputWidth * inputHeight * 3) {
  65120. throw "ConvertPanoramaToCubemap: input size is wrong";
  65121. }
  65122. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65123. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65124. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65125. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65126. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65127. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65128. return {
  65129. front: textureFront,
  65130. back: textureBack,
  65131. left: textureLeft,
  65132. right: textureRight,
  65133. up: textureUp,
  65134. down: textureDown,
  65135. size: size,
  65136. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65137. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65138. gammaSpace: false,
  65139. };
  65140. };
  65141. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65142. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65143. var textureArray = new Float32Array(buffer);
  65144. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65145. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65146. var dy = 1 / texSize;
  65147. var fy = 0;
  65148. for (var y = 0; y < texSize; y++) {
  65149. var xv1 = faceData[0];
  65150. var xv2 = faceData[2];
  65151. for (var x = 0; x < texSize; x++) {
  65152. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65153. v.normalize();
  65154. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65155. // 3 channels per pixels
  65156. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65157. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65158. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65159. xv1 = xv1.add(rotDX1);
  65160. xv2 = xv2.add(rotDX2);
  65161. }
  65162. fy += dy;
  65163. }
  65164. return textureArray;
  65165. };
  65166. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65167. var theta = Math.atan2(vDir.z, vDir.x);
  65168. var phi = Math.acos(vDir.y);
  65169. while (theta < -Math.PI)
  65170. theta += 2 * Math.PI;
  65171. while (theta > Math.PI)
  65172. theta -= 2 * Math.PI;
  65173. var dx = theta / Math.PI;
  65174. var dy = phi / Math.PI;
  65175. // recenter.
  65176. dx = dx * 0.5 + 0.5;
  65177. var px = Math.round(dx * inputWidth);
  65178. if (px < 0)
  65179. px = 0;
  65180. else if (px >= inputWidth)
  65181. px = inputWidth - 1;
  65182. var py = Math.round(dy * inputHeight);
  65183. if (py < 0)
  65184. py = 0;
  65185. else if (py >= inputHeight)
  65186. py = inputHeight - 1;
  65187. var inputY = (inputHeight - py - 1);
  65188. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65189. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65190. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65191. return {
  65192. r: r,
  65193. g: g,
  65194. b: b
  65195. };
  65196. };
  65197. PanoramaToCubeMapTools.FACE_FRONT = [
  65198. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65199. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65200. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65201. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65202. ];
  65203. PanoramaToCubeMapTools.FACE_BACK = [
  65204. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65205. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65206. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65207. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65208. ];
  65209. PanoramaToCubeMapTools.FACE_RIGHT = [
  65210. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65211. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65212. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65213. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65214. ];
  65215. PanoramaToCubeMapTools.FACE_LEFT = [
  65216. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65217. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65218. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65219. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65220. ];
  65221. PanoramaToCubeMapTools.FACE_DOWN = [
  65222. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65223. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65224. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65225. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65226. ];
  65227. PanoramaToCubeMapTools.FACE_UP = [
  65228. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65229. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65230. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65231. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65232. ];
  65233. return PanoramaToCubeMapTools;
  65234. }());
  65235. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65236. })(BABYLON || (BABYLON = {}));
  65237. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65238. var BABYLON;
  65239. (function (BABYLON) {
  65240. ;
  65241. /**
  65242. * This groups tools to convert HDR texture to native colors array.
  65243. */
  65244. var HDRTools = /** @class */ (function () {
  65245. function HDRTools() {
  65246. }
  65247. HDRTools.Ldexp = function (mantissa, exponent) {
  65248. if (exponent > 1023) {
  65249. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65250. }
  65251. if (exponent < -1074) {
  65252. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65253. }
  65254. return mantissa * Math.pow(2, exponent);
  65255. };
  65256. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65257. if (exponent > 0) {
  65258. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65259. float32array[index + 0] = red * exponent;
  65260. float32array[index + 1] = green * exponent;
  65261. float32array[index + 2] = blue * exponent;
  65262. }
  65263. else {
  65264. float32array[index + 0] = 0;
  65265. float32array[index + 1] = 0;
  65266. float32array[index + 2] = 0;
  65267. }
  65268. };
  65269. HDRTools.readStringLine = function (uint8array, startIndex) {
  65270. var line = "";
  65271. var character = "";
  65272. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65273. character = String.fromCharCode(uint8array[i]);
  65274. if (character == "\n") {
  65275. break;
  65276. }
  65277. line += character;
  65278. }
  65279. return line;
  65280. };
  65281. /**
  65282. * Reads header information from an RGBE texture stored in a native array.
  65283. * More information on this format are available here:
  65284. * https://en.wikipedia.org/wiki/RGBE_image_format
  65285. *
  65286. * @param uint8array The binary file stored in native array.
  65287. * @return The header information.
  65288. */
  65289. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65290. var height = 0;
  65291. var width = 0;
  65292. var line = this.readStringLine(uint8array, 0);
  65293. if (line[0] != '#' || line[1] != '?') {
  65294. throw "Bad HDR Format.";
  65295. }
  65296. var endOfHeader = false;
  65297. var findFormat = false;
  65298. var lineIndex = 0;
  65299. do {
  65300. lineIndex += (line.length + 1);
  65301. line = this.readStringLine(uint8array, lineIndex);
  65302. if (line == "FORMAT=32-bit_rle_rgbe") {
  65303. findFormat = true;
  65304. }
  65305. else if (line.length == 0) {
  65306. endOfHeader = true;
  65307. }
  65308. } while (!endOfHeader);
  65309. if (!findFormat) {
  65310. throw "HDR Bad header format, unsupported FORMAT";
  65311. }
  65312. lineIndex += (line.length + 1);
  65313. line = this.readStringLine(uint8array, lineIndex);
  65314. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65315. var match = sizeRegexp.exec(line);
  65316. // TODO. Support +Y and -X if needed.
  65317. if (!match || match.length < 3) {
  65318. throw "HDR Bad header format, no size";
  65319. }
  65320. width = parseInt(match[2]);
  65321. height = parseInt(match[1]);
  65322. if (width < 8 || width > 0x7fff) {
  65323. throw "HDR Bad header format, unsupported size";
  65324. }
  65325. lineIndex += (line.length + 1);
  65326. return {
  65327. height: height,
  65328. width: width,
  65329. dataPosition: lineIndex
  65330. };
  65331. };
  65332. /**
  65333. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65334. * This RGBE texture needs to store the information as a panorama.
  65335. *
  65336. * More information on this format are available here:
  65337. * https://en.wikipedia.org/wiki/RGBE_image_format
  65338. *
  65339. * @param buffer The binary file stored in an array buffer.
  65340. * @param size The expected size of the extracted cubemap.
  65341. * @return The Cube Map information.
  65342. */
  65343. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65344. var uint8array = new Uint8Array(buffer);
  65345. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65346. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65347. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65348. return cubeMapData;
  65349. };
  65350. /**
  65351. * Returns the pixels data extracted from an RGBE texture.
  65352. * This pixels will be stored left to right up to down in the R G B order in one array.
  65353. *
  65354. * More information on this format are available here:
  65355. * https://en.wikipedia.org/wiki/RGBE_image_format
  65356. *
  65357. * @param uint8array The binary file stored in an array buffer.
  65358. * @param hdrInfo The header information of the file.
  65359. * @return The pixels data in RGB right to left up to down order.
  65360. */
  65361. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65362. // Keep for multi format supports.
  65363. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65364. };
  65365. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65366. var num_scanlines = hdrInfo.height;
  65367. var scanline_width = hdrInfo.width;
  65368. var a, b, c, d, count;
  65369. var dataIndex = hdrInfo.dataPosition;
  65370. var index = 0, endIndex = 0, i = 0;
  65371. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65372. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65373. // 3 channels of 4 bytes per pixel in float.
  65374. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65375. var resultArray = new Float32Array(resultBuffer);
  65376. // read in each successive scanline
  65377. while (num_scanlines > 0) {
  65378. a = uint8array[dataIndex++];
  65379. b = uint8array[dataIndex++];
  65380. c = uint8array[dataIndex++];
  65381. d = uint8array[dataIndex++];
  65382. if (a != 2 || b != 2 || (c & 0x80)) {
  65383. // this file is not run length encoded
  65384. throw "HDR Bad header format, not RLE";
  65385. }
  65386. if (((c << 8) | d) != scanline_width) {
  65387. throw "HDR Bad header format, wrong scan line width";
  65388. }
  65389. index = 0;
  65390. // read each of the four channels for the scanline into the buffer
  65391. for (i = 0; i < 4; i++) {
  65392. endIndex = (i + 1) * scanline_width;
  65393. while (index < endIndex) {
  65394. a = uint8array[dataIndex++];
  65395. b = uint8array[dataIndex++];
  65396. if (a > 128) {
  65397. // a run of the same value
  65398. count = a - 128;
  65399. if ((count == 0) || (count > endIndex - index)) {
  65400. throw "HDR Bad Format, bad scanline data (run)";
  65401. }
  65402. while (count-- > 0) {
  65403. scanLineArray[index++] = b;
  65404. }
  65405. }
  65406. else {
  65407. // a non-run
  65408. count = a;
  65409. if ((count == 0) || (count > endIndex - index)) {
  65410. throw "HDR Bad Format, bad scanline data (non-run)";
  65411. }
  65412. scanLineArray[index++] = b;
  65413. if (--count > 0) {
  65414. for (var j = 0; j < count; j++) {
  65415. scanLineArray[index++] = uint8array[dataIndex++];
  65416. }
  65417. }
  65418. }
  65419. }
  65420. }
  65421. // now convert data from buffer into floats
  65422. for (i = 0; i < scanline_width; i++) {
  65423. a = scanLineArray[i];
  65424. b = scanLineArray[i + scanline_width];
  65425. c = scanLineArray[i + 2 * scanline_width];
  65426. d = scanLineArray[i + 3 * scanline_width];
  65427. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65428. }
  65429. num_scanlines--;
  65430. }
  65431. return resultArray;
  65432. };
  65433. return HDRTools;
  65434. }());
  65435. BABYLON.HDRTools = HDRTools;
  65436. })(BABYLON || (BABYLON = {}));
  65437. //# sourceMappingURL=babylon.hdr.js.map
  65438. var BABYLON;
  65439. (function (BABYLON) {
  65440. /**
  65441. * This represents a texture coming from an HDR input.
  65442. *
  65443. * The only supported format is currently panorama picture stored in RGBE format.
  65444. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65445. */
  65446. var HDRCubeTexture = /** @class */ (function (_super) {
  65447. __extends(HDRCubeTexture, _super);
  65448. /**
  65449. * Instantiates an HDRTexture from the following parameters.
  65450. *
  65451. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65452. * @param scene The scene the texture will be used in
  65453. * @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.
  65454. * @param noMipmap Forces to not generate the mipmap if true
  65455. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  65456. * @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)
  65457. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65458. */
  65459. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65460. if (noMipmap === void 0) { noMipmap = false; }
  65461. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65462. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65463. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65464. if (onLoad === void 0) { onLoad = null; }
  65465. if (onError === void 0) { onError = null; }
  65466. var _this = _super.call(this, scene) || this;
  65467. _this._useInGammaSpace = false;
  65468. _this._generateHarmonics = true;
  65469. _this._isBABYLONPreprocessed = false;
  65470. _this._onLoad = null;
  65471. _this._onError = null;
  65472. /**
  65473. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65474. */
  65475. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65476. /**
  65477. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65478. * This is usefull at run time to apply the good shader.
  65479. */
  65480. _this.isPMREM = false;
  65481. _this._isBlocking = true;
  65482. if (!url) {
  65483. return _this;
  65484. }
  65485. _this.name = url;
  65486. _this.url = url;
  65487. _this.hasAlpha = false;
  65488. _this.isCube = true;
  65489. _this._textureMatrix = BABYLON.Matrix.Identity();
  65490. _this._onLoad = onLoad;
  65491. _this._onError = onError;
  65492. _this.gammaSpace = false;
  65493. var caps = scene.getEngine().getCaps();
  65494. if (size) {
  65495. _this._isBABYLONPreprocessed = false;
  65496. _this._noMipmap = noMipmap;
  65497. _this._size = size;
  65498. _this._useInGammaSpace = useInGammaSpace;
  65499. _this._usePMREMGenerator = usePMREMGenerator &&
  65500. caps.textureLOD &&
  65501. caps.textureFloat &&
  65502. !_this._useInGammaSpace;
  65503. }
  65504. else {
  65505. _this._isBABYLONPreprocessed = true;
  65506. _this._noMipmap = false;
  65507. _this._useInGammaSpace = false;
  65508. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65509. !_this._useInGammaSpace;
  65510. }
  65511. _this.isPMREM = _this._usePMREMGenerator;
  65512. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65513. if (!_this._texture) {
  65514. if (!scene.useDelayedTextureLoading) {
  65515. _this.loadTexture();
  65516. }
  65517. else {
  65518. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65519. }
  65520. }
  65521. return _this;
  65522. }
  65523. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65524. /**
  65525. * Gets wether or not the texture is blocking during loading.
  65526. */
  65527. get: function () {
  65528. return this._isBlocking;
  65529. },
  65530. /**
  65531. * Sets wether or not the texture is blocking during loading.
  65532. */
  65533. set: function (value) {
  65534. this._isBlocking = value;
  65535. },
  65536. enumerable: true,
  65537. configurable: true
  65538. });
  65539. /**
  65540. * Occurs when the file is a preprocessed .babylon.hdr file.
  65541. */
  65542. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65543. var _this = this;
  65544. var mipLevels = 0;
  65545. var floatArrayView = null;
  65546. var scene = this.getScene();
  65547. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65548. var mips = new Array();
  65549. if (!floatArrayView) {
  65550. return mips;
  65551. }
  65552. var startIndex = 30;
  65553. for (var level = 0; level < mipLevels; level++) {
  65554. mips.push([]);
  65555. // Fill each pixel of the mip level.
  65556. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65557. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65558. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65559. mips[level].push(faceData);
  65560. startIndex += faceSize;
  65561. }
  65562. }
  65563. return mips;
  65564. } : null;
  65565. var callback = function (buffer) {
  65566. var scene = _this.getScene();
  65567. if (!scene) {
  65568. return null;
  65569. }
  65570. // Create Native Array Views
  65571. var intArrayView = new Int32Array(buffer);
  65572. floatArrayView = new Float32Array(buffer);
  65573. // Fill header.
  65574. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65575. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65576. // Update Texture Information.
  65577. if (!_this._texture) {
  65578. return null;
  65579. }
  65580. _this._texture.updateSize(_this._size, _this._size);
  65581. // Fill polynomial information.
  65582. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65583. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65584. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65585. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65586. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65587. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65588. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65589. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65590. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65591. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65592. _this.sphericalPolynomial = sphericalPolynomial;
  65593. // Fill pixel data.
  65594. mipLevels = intArrayView[29]; // Number of mip levels.
  65595. var startIndex = 30;
  65596. var data = [];
  65597. var faceSize = Math.pow(_this._size, 2) * 3;
  65598. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65599. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65600. startIndex += faceSize;
  65601. }
  65602. var results = [];
  65603. var byteArray = null;
  65604. // Push each faces.
  65605. for (var k = 0; k < 6; k++) {
  65606. var dataFace = null;
  65607. // To be deprecated.
  65608. if (version === 1) {
  65609. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65610. dataFace = data[j];
  65611. }
  65612. // If special cases.
  65613. if (!mipmapGenerator && dataFace) {
  65614. if (!scene.getEngine().getCaps().textureFloat) {
  65615. // 3 channels of 1 bytes per pixel in bytes.
  65616. var byteBuffer = new ArrayBuffer(faceSize);
  65617. byteArray = new Uint8Array(byteBuffer);
  65618. }
  65619. for (var i = 0; i < _this._size * _this._size; i++) {
  65620. // Put in gamma space if requested.
  65621. if (_this._useInGammaSpace) {
  65622. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65623. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65624. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65625. }
  65626. // Convert to int texture for fallback.
  65627. if (byteArray) {
  65628. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65629. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65630. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65631. // May use luminance instead if the result is not accurate.
  65632. var max = Math.max(Math.max(r, g), b);
  65633. if (max > 255) {
  65634. var scale = 255 / max;
  65635. r *= scale;
  65636. g *= scale;
  65637. b *= scale;
  65638. }
  65639. byteArray[(i * 3) + 0] = r;
  65640. byteArray[(i * 3) + 1] = g;
  65641. byteArray[(i * 3) + 2] = b;
  65642. }
  65643. }
  65644. }
  65645. // Fill the array accordingly.
  65646. if (byteArray) {
  65647. results.push(byteArray);
  65648. }
  65649. else {
  65650. results.push(dataFace);
  65651. }
  65652. }
  65653. return results;
  65654. };
  65655. if (scene) {
  65656. 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);
  65657. }
  65658. };
  65659. /**
  65660. * Occurs when the file is raw .hdr file.
  65661. */
  65662. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65663. var _this = this;
  65664. var callback = function (buffer) {
  65665. var scene = _this.getScene();
  65666. if (!scene) {
  65667. return null;
  65668. }
  65669. // Extract the raw linear data.
  65670. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65671. // Generate harmonics if needed.
  65672. if (_this._generateHarmonics) {
  65673. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65674. _this.sphericalPolynomial = sphericalPolynomial;
  65675. }
  65676. var results = [];
  65677. var byteArray = null;
  65678. // Push each faces.
  65679. for (var j = 0; j < 6; j++) {
  65680. // Create uintarray fallback.
  65681. if (!scene.getEngine().getCaps().textureFloat) {
  65682. // 3 channels of 1 bytes per pixel in bytes.
  65683. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65684. byteArray = new Uint8Array(byteBuffer);
  65685. }
  65686. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65687. // If special cases.
  65688. if (_this._useInGammaSpace || byteArray) {
  65689. for (var i = 0; i < _this._size * _this._size; i++) {
  65690. // Put in gamma space if requested.
  65691. if (_this._useInGammaSpace) {
  65692. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65693. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65694. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65695. }
  65696. // Convert to int texture for fallback.
  65697. if (byteArray) {
  65698. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65699. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65700. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65701. // May use luminance instead if the result is not accurate.
  65702. var max = Math.max(Math.max(r, g), b);
  65703. if (max > 255) {
  65704. var scale = 255 / max;
  65705. r *= scale;
  65706. g *= scale;
  65707. b *= scale;
  65708. }
  65709. byteArray[(i * 3) + 0] = r;
  65710. byteArray[(i * 3) + 1] = g;
  65711. byteArray[(i * 3) + 2] = b;
  65712. }
  65713. }
  65714. }
  65715. if (byteArray) {
  65716. results.push(byteArray);
  65717. }
  65718. else {
  65719. results.push(dataFace);
  65720. }
  65721. }
  65722. return results;
  65723. };
  65724. var mipmapGenerator = null;
  65725. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  65726. // if (!this._noMipmap &&
  65727. // this._usePMREMGenerator) {
  65728. // mipmapGenerator = (data: ArrayBufferView[]) => {
  65729. // // Custom setup of the generator matching with the PBR shader values.
  65730. // var generator = new BABYLON.PMREMGenerator(data,
  65731. // this._size,
  65732. // this._size,
  65733. // 0,
  65734. // 3,
  65735. // this.getScene().getEngine().getCaps().textureFloat,
  65736. // 2048,
  65737. // 0.25,
  65738. // false,
  65739. // true);
  65740. // return generator.filterCubeMap();
  65741. // };
  65742. // }
  65743. var scene = this.getScene();
  65744. if (scene) {
  65745. 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);
  65746. }
  65747. };
  65748. /**
  65749. * Starts the loading process of the texture.
  65750. */
  65751. HDRCubeTexture.prototype.loadTexture = function () {
  65752. if (this._isBABYLONPreprocessed) {
  65753. this.loadBabylonTexture();
  65754. }
  65755. else {
  65756. this.loadHDRTexture();
  65757. }
  65758. };
  65759. HDRCubeTexture.prototype.clone = function () {
  65760. var scene = this.getScene();
  65761. if (!scene) {
  65762. return this;
  65763. }
  65764. var size = (this._isBABYLONPreprocessed ? null : this._size);
  65765. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  65766. // Base texture
  65767. newTexture.level = this.level;
  65768. newTexture.wrapU = this.wrapU;
  65769. newTexture.wrapV = this.wrapV;
  65770. newTexture.coordinatesIndex = this.coordinatesIndex;
  65771. newTexture.coordinatesMode = this.coordinatesMode;
  65772. return newTexture;
  65773. };
  65774. // Methods
  65775. HDRCubeTexture.prototype.delayLoad = function () {
  65776. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65777. return;
  65778. }
  65779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65780. this._texture = this._getFromCache(this.url, this._noMipmap);
  65781. if (!this._texture) {
  65782. this.loadTexture();
  65783. }
  65784. };
  65785. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  65786. return this._textureMatrix;
  65787. };
  65788. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65789. this._textureMatrix = value;
  65790. };
  65791. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65792. var texture = null;
  65793. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65794. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  65795. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  65796. texture.name = parsedTexture.name;
  65797. texture.hasAlpha = parsedTexture.hasAlpha;
  65798. texture.level = parsedTexture.level;
  65799. texture.coordinatesMode = parsedTexture.coordinatesMode;
  65800. texture.isBlocking = parsedTexture.isBlocking;
  65801. }
  65802. return texture;
  65803. };
  65804. HDRCubeTexture.prototype.serialize = function () {
  65805. if (!this.name) {
  65806. return null;
  65807. }
  65808. var serializationObject = {};
  65809. serializationObject.name = this.name;
  65810. serializationObject.hasAlpha = this.hasAlpha;
  65811. serializationObject.isCube = true;
  65812. serializationObject.level = this.level;
  65813. serializationObject.size = this._size;
  65814. serializationObject.coordinatesMode = this.coordinatesMode;
  65815. serializationObject.useInGammaSpace = this._useInGammaSpace;
  65816. serializationObject.generateHarmonics = this._generateHarmonics;
  65817. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  65818. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  65819. serializationObject.customType = "BABYLON.HDRCubeTexture";
  65820. serializationObject.noMipmap = this._noMipmap;
  65821. serializationObject.isBlocking = this._isBlocking;
  65822. return serializationObject;
  65823. };
  65824. /**
  65825. * Saves as a file the data contained in the texture in a binary format.
  65826. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65827. * as the spherical used in the lighting.
  65828. * @param url The HDR file url.
  65829. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65830. * @param onError Method called if any error happens during download.
  65831. * @return The packed binary data.
  65832. */
  65833. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  65834. if (onError === void 0) { onError = null; }
  65835. var callback = function (buffer) {
  65836. var data = new Blob([buffer], { type: 'application/octet-stream' });
  65837. // Returns a URL you can use as a href.
  65838. var objUrl = window.URL.createObjectURL(data);
  65839. // Simulates a link to it and click to dowload.
  65840. var a = document.createElement("a");
  65841. document.body.appendChild(a);
  65842. a.style.display = "none";
  65843. a.href = objUrl;
  65844. a.download = "envmap.babylon.hdr";
  65845. a.click();
  65846. };
  65847. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  65848. };
  65849. /**
  65850. * Serializes the data contained in the texture in a binary format.
  65851. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65852. * as the spherical used in the lighting.
  65853. * @param url The HDR file url.
  65854. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65855. * @param onError Method called if any error happens during download.
  65856. * @return The packed binary data.
  65857. */
  65858. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  65859. if (onError === void 0) { onError = null; }
  65860. // Needs the url tho create the texture.
  65861. if (!url) {
  65862. return;
  65863. }
  65864. // Check Power of two size.
  65865. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  65866. return;
  65867. }
  65868. // Coming Back in 3.x.
  65869. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  65870. };
  65871. HDRCubeTexture._facesMapping = [
  65872. "right",
  65873. "left",
  65874. "up",
  65875. "down",
  65876. "front",
  65877. "back"
  65878. ];
  65879. return HDRCubeTexture;
  65880. }(BABYLON.BaseTexture));
  65881. BABYLON.HDRCubeTexture = HDRCubeTexture;
  65882. })(BABYLON || (BABYLON = {}));
  65883. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  65884. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  65885. // Huge respect for a such great lib.
  65886. // Earcut license:
  65887. // Copyright (c) 2016, Mapbox
  65888. //
  65889. // Permission to use, copy, modify, and/or distribute this software for any purpose
  65890. // with or without fee is hereby granted, provided that the above copyright notice
  65891. // and this permission notice appear in all copies.
  65892. //
  65893. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  65894. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  65895. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  65896. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  65897. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  65898. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  65899. // THIS SOFTWARE.
  65900. var Earcut;
  65901. (function (Earcut) {
  65902. /**
  65903. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  65904. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  65905. * @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).
  65906. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  65907. */
  65908. function earcut(data, holeIndices, dim) {
  65909. dim = dim || 2;
  65910. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  65911. if (!outerNode)
  65912. return triangles;
  65913. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  65914. if (hasHoles)
  65915. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  65916. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  65917. if (data.length > 80 * dim) {
  65918. minX = maxX = data[0];
  65919. minY = maxY = data[1];
  65920. for (var i = dim; i < outerLen; i += dim) {
  65921. x = data[i];
  65922. y = data[i + 1];
  65923. if (x < minX)
  65924. minX = x;
  65925. if (y < minY)
  65926. minY = y;
  65927. if (x > maxX)
  65928. maxX = x;
  65929. if (y > maxY)
  65930. maxY = y;
  65931. }
  65932. // minX, minY and size are later used to transform coords into integers for z-order calculation
  65933. size = Math.max(maxX - minX, maxY - minY);
  65934. }
  65935. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  65936. return triangles;
  65937. }
  65938. Earcut.earcut = earcut;
  65939. var Node = /** @class */ (function () {
  65940. function Node(i, x, y) {
  65941. this.i = i;
  65942. this.x = x;
  65943. this.y = y;
  65944. this.prev = null;
  65945. this.next = null;
  65946. this.z = null;
  65947. this.prevZ = null;
  65948. this.nextZ = null;
  65949. this.steiner = false;
  65950. }
  65951. return Node;
  65952. }());
  65953. // create a circular doubly linked list from polygon points in the specified winding order
  65954. function linkedList(data, start, end, dim, clockwise) {
  65955. var i, last = null;
  65956. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  65957. for (i = start; i < end; i += dim)
  65958. last = insertNode(i, data[i], data[i + 1], last);
  65959. }
  65960. else {
  65961. for (i = end - dim; i >= start; i -= dim)
  65962. last = insertNode(i, data[i], data[i + 1], last);
  65963. }
  65964. if (last && equals(last, last.next)) {
  65965. removeNode(last);
  65966. last = last.next;
  65967. }
  65968. return last;
  65969. }
  65970. // eliminate colinear or duplicate points
  65971. function filterPoints(start, end) {
  65972. if (!start)
  65973. return start;
  65974. if (!end)
  65975. end = start;
  65976. var p = start, again;
  65977. do {
  65978. again = false;
  65979. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  65980. removeNode(p);
  65981. p = end = p.prev;
  65982. if (p === p.next)
  65983. return undefined;
  65984. again = true;
  65985. }
  65986. else {
  65987. p = p.next;
  65988. }
  65989. } while (again || p !== end);
  65990. return end;
  65991. }
  65992. // main ear slicing loop which triangulates a polygon (given as a linked list)
  65993. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  65994. if (!ear)
  65995. return;
  65996. // interlink polygon nodes in z-order
  65997. if (!pass && size)
  65998. indexCurve(ear, minX, minY, size);
  65999. var stop = ear, prev, next;
  66000. // iterate through ears, slicing them one by one
  66001. while (ear.prev !== ear.next) {
  66002. prev = ear.prev;
  66003. next = ear.next;
  66004. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66005. // cut off the triangle
  66006. triangles.push(prev.i / dim);
  66007. triangles.push(ear.i / dim);
  66008. triangles.push(next.i / dim);
  66009. removeNode(ear);
  66010. // skipping the next vertice leads to less sliver triangles
  66011. ear = next.next;
  66012. stop = next.next;
  66013. continue;
  66014. }
  66015. ear = next;
  66016. // if we looped through the whole remaining polygon and can't find any more ears
  66017. if (ear === stop) {
  66018. // try filtering points and slicing again
  66019. if (!pass) {
  66020. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66021. // if this didn't work, try curing all small self-intersections locally
  66022. }
  66023. else if (pass === 1) {
  66024. ear = cureLocalIntersections(ear, triangles, dim);
  66025. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66026. // as a last resort, try splitting the remaining polygon into two
  66027. }
  66028. else if (pass === 2) {
  66029. splitEarcut(ear, triangles, dim, minX, minY, size);
  66030. }
  66031. break;
  66032. }
  66033. }
  66034. }
  66035. // check whether a polygon node forms a valid ear with adjacent nodes
  66036. function isEar(ear) {
  66037. var a = ear.prev, b = ear, c = ear.next;
  66038. if (area(a, b, c) >= 0)
  66039. return false; // reflex, can't be an ear
  66040. // now make sure we don't have other points inside the potential ear
  66041. var p = ear.next.next;
  66042. while (p !== ear.prev) {
  66043. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66044. area(p.prev, p, p.next) >= 0)
  66045. return false;
  66046. p = p.next;
  66047. }
  66048. return true;
  66049. }
  66050. function isEarHashed(ear, minX, minY, size) {
  66051. var a = ear.prev, b = ear, c = ear.next;
  66052. if (area(a, b, c) >= 0)
  66053. return false; // reflex, can't be an ear
  66054. // triangle bbox; min & max are calculated like this for speed
  66055. 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);
  66056. // z-order range for the current triangle bbox;
  66057. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66058. // first look for points inside the triangle in increasing z-order
  66059. var p = ear.nextZ;
  66060. while (p && p.z <= maxZ) {
  66061. if (p !== ear.prev &&
  66062. p !== ear.next &&
  66063. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66064. area(p.prev, p, p.next) >= 0)
  66065. return false;
  66066. p = p.nextZ;
  66067. }
  66068. // then look for points in decreasing z-order
  66069. p = ear.prevZ;
  66070. while (p && p.z >= minZ) {
  66071. if (p !== ear.prev &&
  66072. p !== ear.next &&
  66073. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66074. area(p.prev, p, p.next) >= 0)
  66075. return false;
  66076. p = p.prevZ;
  66077. }
  66078. return true;
  66079. }
  66080. // go through all polygon nodes and cure small local self-intersections
  66081. function cureLocalIntersections(start, triangles, dim) {
  66082. var p = start;
  66083. do {
  66084. var a = p.prev, b = p.next.next;
  66085. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66086. triangles.push(a.i / dim);
  66087. triangles.push(p.i / dim);
  66088. triangles.push(b.i / dim);
  66089. // remove two nodes involved
  66090. removeNode(p);
  66091. removeNode(p.next);
  66092. p = start = b;
  66093. }
  66094. p = p.next;
  66095. } while (p !== start);
  66096. return p;
  66097. }
  66098. // try splitting polygon into two and triangulate them independently
  66099. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66100. // look for a valid diagonal that divides the polygon into two
  66101. var a = start;
  66102. do {
  66103. var b = a.next.next;
  66104. while (b !== a.prev) {
  66105. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66106. // split the polygon in two by the diagonal
  66107. var c = splitPolygon(a, b);
  66108. // filter colinear points around the cuts
  66109. a = filterPoints(a, a.next);
  66110. c = filterPoints(c, c.next);
  66111. // run earcut on each half
  66112. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66113. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66114. return;
  66115. }
  66116. b = b.next;
  66117. }
  66118. a = a.next;
  66119. } while (a !== start);
  66120. }
  66121. // link every hole into the outer loop, producing a single-ring polygon without holes
  66122. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66123. var queue = [], i, len, start, end, list;
  66124. for (i = 0, len = holeIndices.length; i < len; i++) {
  66125. start = holeIndices[i] * dim;
  66126. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66127. list = linkedList(data, start, end, dim, false);
  66128. if (list === list.next)
  66129. list.steiner = true;
  66130. queue.push(getLeftmost(list));
  66131. }
  66132. queue.sort(compareX);
  66133. // process holes from left to right
  66134. for (i = 0; i < queue.length; i++) {
  66135. eliminateHole(queue[i], outerNode);
  66136. outerNode = filterPoints(outerNode, outerNode.next);
  66137. }
  66138. return outerNode;
  66139. }
  66140. function compareX(a, b) {
  66141. return a.x - b.x;
  66142. }
  66143. // find a bridge between vertices that connects hole with an outer ring and and link it
  66144. function eliminateHole(hole, outerNode) {
  66145. outerNode = findHoleBridge(hole, outerNode);
  66146. if (outerNode) {
  66147. var b = splitPolygon(outerNode, hole);
  66148. filterPoints(b, b.next);
  66149. }
  66150. }
  66151. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66152. function findHoleBridge(hole, outerNode) {
  66153. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66154. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66155. // segment's endpoint with lesser x will be potential connection point
  66156. do {
  66157. if (hy <= p.y && hy >= p.next.y) {
  66158. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66159. if (x <= hx && x > qx) {
  66160. qx = x;
  66161. if (x === hx) {
  66162. if (hy === p.y)
  66163. return p;
  66164. if (hy === p.next.y)
  66165. return p.next;
  66166. }
  66167. m = p.x < p.next.x ? p : p.next;
  66168. }
  66169. }
  66170. p = p.next;
  66171. } while (p !== outerNode);
  66172. if (!m)
  66173. return null;
  66174. if (hx === qx)
  66175. return m.prev; // hole touches outer segment; pick lower endpoint
  66176. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66177. // if there are no points found, we have a valid connection;
  66178. // otherwise choose the point of the minimum angle with the ray as connection point
  66179. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66180. p = m.next;
  66181. while (p !== stop) {
  66182. if (hx >= p.x &&
  66183. p.x >= mx &&
  66184. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66185. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66186. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66187. m = p;
  66188. tanMin = tan;
  66189. }
  66190. }
  66191. p = p.next;
  66192. }
  66193. return m;
  66194. }
  66195. // interlink polygon nodes in z-order
  66196. function indexCurve(start, minX, minY, size) {
  66197. var p = start;
  66198. do {
  66199. if (p.z === null)
  66200. p.z = zOrder(p.x, p.y, minX, minY, size);
  66201. p.prevZ = p.prev;
  66202. p.nextZ = p.next;
  66203. p = p.next;
  66204. } while (p !== start);
  66205. p.prevZ.nextZ = null;
  66206. p.prevZ = null;
  66207. sortLinked(p);
  66208. }
  66209. // Simon Tatham's linked list merge sort algorithm
  66210. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66211. function sortLinked(list) {
  66212. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66213. do {
  66214. p = list;
  66215. list = null;
  66216. tail = null;
  66217. numMerges = 0;
  66218. while (p) {
  66219. numMerges++;
  66220. q = p;
  66221. pSize = 0;
  66222. for (i = 0; i < inSize; i++) {
  66223. pSize++;
  66224. q = q.nextZ;
  66225. if (!q)
  66226. break;
  66227. }
  66228. qSize = inSize;
  66229. while (pSize > 0 || (qSize > 0 && q)) {
  66230. if (pSize === 0) {
  66231. e = q;
  66232. q = q.nextZ;
  66233. qSize--;
  66234. }
  66235. else if (qSize === 0 || !q) {
  66236. e = p;
  66237. p = p.nextZ;
  66238. pSize--;
  66239. }
  66240. else if (p.z <= q.z) {
  66241. e = p;
  66242. p = p.nextZ;
  66243. pSize--;
  66244. }
  66245. else {
  66246. e = q;
  66247. q = q.nextZ;
  66248. qSize--;
  66249. }
  66250. if (tail)
  66251. tail.nextZ = e;
  66252. else
  66253. list = e;
  66254. e.prevZ = tail;
  66255. tail = e;
  66256. }
  66257. p = q;
  66258. }
  66259. tail.nextZ = null;
  66260. inSize *= 2;
  66261. } while (numMerges > 1);
  66262. return list;
  66263. }
  66264. // z-order of a point given coords and size of the data bounding box
  66265. function zOrder(x, y, minX, minY, size) {
  66266. // coords are transformed into non-negative 15-bit integer range
  66267. x = 32767 * (x - minX) / size;
  66268. y = 32767 * (y - minY) / size;
  66269. x = (x | (x << 8)) & 0x00FF00FF;
  66270. x = (x | (x << 4)) & 0x0F0F0F0F;
  66271. x = (x | (x << 2)) & 0x33333333;
  66272. x = (x | (x << 1)) & 0x55555555;
  66273. y = (y | (y << 8)) & 0x00FF00FF;
  66274. y = (y | (y << 4)) & 0x0F0F0F0F;
  66275. y = (y | (y << 2)) & 0x33333333;
  66276. y = (y | (y << 1)) & 0x55555555;
  66277. return x | (y << 1);
  66278. }
  66279. // find the leftmost node of a polygon ring
  66280. function getLeftmost(start) {
  66281. var p = start, leftmost = start;
  66282. do {
  66283. if (p.x < leftmost.x)
  66284. leftmost = p;
  66285. p = p.next;
  66286. } while (p !== start);
  66287. return leftmost;
  66288. }
  66289. // check if a point lies within a convex triangle
  66290. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66291. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66292. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66293. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66294. }
  66295. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66296. function isValidDiagonal(a, b) {
  66297. return a.next.i !== b.i &&
  66298. a.prev.i !== b.i &&
  66299. !intersectsPolygon(a, b) &&
  66300. locallyInside(a, b) &&
  66301. locallyInside(b, a) &&
  66302. middleInside(a, b);
  66303. }
  66304. // signed area of a triangle
  66305. function area(p, q, r) {
  66306. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66307. }
  66308. // check if two points are equal
  66309. function equals(p1, p2) {
  66310. return p1.x === p2.x && p1.y === p2.y;
  66311. }
  66312. // check if two segments intersect
  66313. function intersects(p1, q1, p2, q2) {
  66314. if ((equals(p1, q1) && equals(p2, q2)) ||
  66315. (equals(p1, q2) && equals(p2, q1)))
  66316. return true;
  66317. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66318. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66319. }
  66320. // check if a polygon diagonal intersects any polygon segments
  66321. function intersectsPolygon(a, b) {
  66322. var p = a;
  66323. do {
  66324. if (p.i !== a.i &&
  66325. p.next.i !== a.i &&
  66326. p.i !== b.i &&
  66327. p.next.i !== b.i &&
  66328. intersects(p, p.next, a, b))
  66329. return true;
  66330. p = p.next;
  66331. } while (p !== a);
  66332. return false;
  66333. }
  66334. // check if a polygon diagonal is locally inside the polygon
  66335. function locallyInside(a, b) {
  66336. return area(a.prev, a, a.next) < 0
  66337. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66338. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66339. }
  66340. // check if the middle point of a polygon diagonal is inside the polygon
  66341. function middleInside(a, b) {
  66342. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66343. do {
  66344. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66345. inside = !inside;
  66346. p = p.next;
  66347. } while (p !== a);
  66348. return inside;
  66349. }
  66350. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66351. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66352. function splitPolygon(a, b) {
  66353. 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;
  66354. a.next = b;
  66355. b.prev = a;
  66356. a2.next = an;
  66357. an.prev = a2;
  66358. b2.next = a2;
  66359. a2.prev = b2;
  66360. bp.next = b2;
  66361. b2.prev = bp;
  66362. return b2;
  66363. }
  66364. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66365. function insertNode(i, x, y, last) {
  66366. var p = new Node(i, x, y);
  66367. if (!last) {
  66368. p.prev = p;
  66369. p.next = p;
  66370. }
  66371. else {
  66372. p.next = last.next;
  66373. p.prev = last;
  66374. last.next.prev = p;
  66375. last.next = p;
  66376. }
  66377. return p;
  66378. }
  66379. function removeNode(p) {
  66380. p.next.prev = p.prev;
  66381. p.prev.next = p.next;
  66382. if (p.prevZ)
  66383. p.prevZ.nextZ = p.nextZ;
  66384. if (p.nextZ)
  66385. p.nextZ.prevZ = p.prevZ;
  66386. }
  66387. /**
  66388. * return a percentage difference between the polygon area and its triangulation area;
  66389. * used to verify correctness of triangulation
  66390. */
  66391. function deviation(data, holeIndices, dim, triangles) {
  66392. var hasHoles = holeIndices && holeIndices.length;
  66393. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66394. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66395. if (hasHoles) {
  66396. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66397. var start = holeIndices[i] * dim;
  66398. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66399. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66400. }
  66401. }
  66402. var trianglesArea = 0;
  66403. for (i = 0; i < triangles.length; i += 3) {
  66404. var a = triangles[i] * dim;
  66405. var b = triangles[i + 1] * dim;
  66406. var c = triangles[i + 2] * dim;
  66407. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66408. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66409. }
  66410. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66411. }
  66412. Earcut.deviation = deviation;
  66413. ;
  66414. function signedArea(data, start, end, dim) {
  66415. var sum = 0;
  66416. for (var i = start, j = end - dim; i < end; i += dim) {
  66417. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66418. j = i;
  66419. }
  66420. return sum;
  66421. }
  66422. /**
  66423. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66424. */
  66425. function flatten(data) {
  66426. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66427. for (var i = 0; i < data.length; i++) {
  66428. for (var j = 0; j < data[i].length; j++) {
  66429. for (var d = 0; d < dim; d++)
  66430. result.vertices.push(data[i][j][d]);
  66431. }
  66432. if (i > 0) {
  66433. holeIndex += data[i - 1].length;
  66434. result.holes.push(holeIndex);
  66435. }
  66436. }
  66437. return result;
  66438. }
  66439. Earcut.flatten = flatten;
  66440. ;
  66441. })(Earcut || (Earcut = {}));
  66442. //# sourceMappingURL=babylon.earcut.js.map
  66443. var BABYLON;
  66444. (function (BABYLON) {
  66445. var IndexedVector2 = /** @class */ (function (_super) {
  66446. __extends(IndexedVector2, _super);
  66447. function IndexedVector2(original, index) {
  66448. var _this = _super.call(this, original.x, original.y) || this;
  66449. _this.index = index;
  66450. return _this;
  66451. }
  66452. return IndexedVector2;
  66453. }(BABYLON.Vector2));
  66454. var PolygonPoints = /** @class */ (function () {
  66455. function PolygonPoints() {
  66456. this.elements = new Array();
  66457. }
  66458. PolygonPoints.prototype.add = function (originalPoints) {
  66459. var _this = this;
  66460. var result = new Array();
  66461. originalPoints.forEach(function (point) {
  66462. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66463. var newPoint = new IndexedVector2(point, _this.elements.length);
  66464. result.push(newPoint);
  66465. _this.elements.push(newPoint);
  66466. }
  66467. });
  66468. return result;
  66469. };
  66470. PolygonPoints.prototype.computeBounds = function () {
  66471. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66472. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66473. this.elements.forEach(function (point) {
  66474. // x
  66475. if (point.x < lmin.x) {
  66476. lmin.x = point.x;
  66477. }
  66478. else if (point.x > lmax.x) {
  66479. lmax.x = point.x;
  66480. }
  66481. // y
  66482. if (point.y < lmin.y) {
  66483. lmin.y = point.y;
  66484. }
  66485. else if (point.y > lmax.y) {
  66486. lmax.y = point.y;
  66487. }
  66488. });
  66489. return {
  66490. min: lmin,
  66491. max: lmax,
  66492. width: lmax.x - lmin.x,
  66493. height: lmax.y - lmin.y
  66494. };
  66495. };
  66496. return PolygonPoints;
  66497. }());
  66498. var Polygon = /** @class */ (function () {
  66499. function Polygon() {
  66500. }
  66501. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66502. return [
  66503. new BABYLON.Vector2(xmin, ymin),
  66504. new BABYLON.Vector2(xmax, ymin),
  66505. new BABYLON.Vector2(xmax, ymax),
  66506. new BABYLON.Vector2(xmin, ymax)
  66507. ];
  66508. };
  66509. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66510. if (cx === void 0) { cx = 0; }
  66511. if (cy === void 0) { cy = 0; }
  66512. if (numberOfSides === void 0) { numberOfSides = 32; }
  66513. var result = new Array();
  66514. var angle = 0;
  66515. var increment = (Math.PI * 2) / numberOfSides;
  66516. for (var i = 0; i < numberOfSides; i++) {
  66517. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66518. angle -= increment;
  66519. }
  66520. return result;
  66521. };
  66522. Polygon.Parse = function (input) {
  66523. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66524. var i, result = [];
  66525. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66526. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66527. }
  66528. return result;
  66529. };
  66530. Polygon.StartingAt = function (x, y) {
  66531. return BABYLON.Path2.StartingAt(x, y);
  66532. };
  66533. return Polygon;
  66534. }());
  66535. BABYLON.Polygon = Polygon;
  66536. var PolygonMeshBuilder = /** @class */ (function () {
  66537. function PolygonMeshBuilder(name, contours, scene) {
  66538. this._points = new PolygonPoints();
  66539. this._outlinepoints = new PolygonPoints();
  66540. this._holes = new Array();
  66541. this._epoints = new Array();
  66542. this._eholes = new Array();
  66543. this._name = name;
  66544. this._scene = scene;
  66545. var points;
  66546. if (contours instanceof BABYLON.Path2) {
  66547. points = contours.getPoints();
  66548. }
  66549. else {
  66550. points = contours;
  66551. }
  66552. this._addToepoint(points);
  66553. this._points.add(points);
  66554. this._outlinepoints.add(points);
  66555. }
  66556. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66557. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66558. var p = points_1[_i];
  66559. this._epoints.push(p.x, p.y);
  66560. }
  66561. };
  66562. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66563. this._points.add(hole);
  66564. var holepoints = new PolygonPoints();
  66565. holepoints.add(hole);
  66566. this._holes.push(holepoints);
  66567. this._eholes.push(this._epoints.length / 2);
  66568. this._addToepoint(hole);
  66569. return this;
  66570. };
  66571. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66572. var _this = this;
  66573. if (updatable === void 0) { updatable = false; }
  66574. if (depth === void 0) { depth = 0; }
  66575. var result = new BABYLON.Mesh(this._name, this._scene);
  66576. var normals = new Array();
  66577. var positions = new Array();
  66578. var uvs = new Array();
  66579. var bounds = this._points.computeBounds();
  66580. this._points.elements.forEach(function (p) {
  66581. normals.push(0, 1.0, 0);
  66582. positions.push(p.x, 0, p.y);
  66583. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66584. });
  66585. var indices = new Array();
  66586. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66587. for (var i = 0; i < res.length; i++) {
  66588. indices.push(res[i]);
  66589. }
  66590. if (depth > 0) {
  66591. var positionscount = (positions.length / 3); //get the current pointcount
  66592. this._points.elements.forEach(function (p) {
  66593. normals.push(0, -1.0, 0);
  66594. positions.push(p.x, -depth, p.y);
  66595. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66596. });
  66597. var totalCount = indices.length;
  66598. for (var i = 0; i < totalCount; i += 3) {
  66599. var i0 = indices[i + 0];
  66600. var i1 = indices[i + 1];
  66601. var i2 = indices[i + 2];
  66602. indices.push(i2 + positionscount);
  66603. indices.push(i1 + positionscount);
  66604. indices.push(i0 + positionscount);
  66605. }
  66606. //Add the sides
  66607. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66608. this._holes.forEach(function (hole) {
  66609. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66610. });
  66611. }
  66612. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66613. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66614. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66615. result.setIndices(indices);
  66616. return result;
  66617. };
  66618. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66619. var StartIndex = positions.length / 3;
  66620. var ulength = 0;
  66621. for (var i = 0; i < points.elements.length; i++) {
  66622. var p = points.elements[i];
  66623. var p1;
  66624. if ((i + 1) > points.elements.length - 1) {
  66625. p1 = points.elements[0];
  66626. }
  66627. else {
  66628. p1 = points.elements[i + 1];
  66629. }
  66630. positions.push(p.x, 0, p.y);
  66631. positions.push(p.x, -depth, p.y);
  66632. positions.push(p1.x, 0, p1.y);
  66633. positions.push(p1.x, -depth, p1.y);
  66634. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66635. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66636. var v3 = v2.subtract(v1);
  66637. var v4 = new BABYLON.Vector3(0, 1, 0);
  66638. var vn = BABYLON.Vector3.Cross(v3, v4);
  66639. vn = vn.normalize();
  66640. uvs.push(ulength / bounds.width, 0);
  66641. uvs.push(ulength / bounds.width, 1);
  66642. ulength += v3.length();
  66643. uvs.push((ulength / bounds.width), 0);
  66644. uvs.push((ulength / bounds.width), 1);
  66645. if (!flip) {
  66646. normals.push(-vn.x, -vn.y, -vn.z);
  66647. normals.push(-vn.x, -vn.y, -vn.z);
  66648. normals.push(-vn.x, -vn.y, -vn.z);
  66649. normals.push(-vn.x, -vn.y, -vn.z);
  66650. indices.push(StartIndex);
  66651. indices.push(StartIndex + 1);
  66652. indices.push(StartIndex + 2);
  66653. indices.push(StartIndex + 1);
  66654. indices.push(StartIndex + 3);
  66655. indices.push(StartIndex + 2);
  66656. }
  66657. else {
  66658. normals.push(vn.x, vn.y, vn.z);
  66659. normals.push(vn.x, vn.y, vn.z);
  66660. normals.push(vn.x, vn.y, vn.z);
  66661. normals.push(vn.x, vn.y, vn.z);
  66662. indices.push(StartIndex);
  66663. indices.push(StartIndex + 2);
  66664. indices.push(StartIndex + 1);
  66665. indices.push(StartIndex + 1);
  66666. indices.push(StartIndex + 2);
  66667. indices.push(StartIndex + 3);
  66668. }
  66669. StartIndex += 4;
  66670. }
  66671. ;
  66672. };
  66673. return PolygonMeshBuilder;
  66674. }());
  66675. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66676. })(BABYLON || (BABYLON = {}));
  66677. //# sourceMappingURL=babylon.polygonMesh.js.map
  66678. var BABYLON;
  66679. (function (BABYLON) {
  66680. // Unique ID when we import meshes from Babylon to CSG
  66681. var currentCSGMeshId = 0;
  66682. // # class Vertex
  66683. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66684. // one to provide additional features like texture coordinates and vertex
  66685. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66686. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66687. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66688. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66689. // is not used anywhere else.
  66690. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66691. var Vertex = /** @class */ (function () {
  66692. function Vertex(pos, normal, uv) {
  66693. this.pos = pos;
  66694. this.normal = normal;
  66695. this.uv = uv;
  66696. }
  66697. Vertex.prototype.clone = function () {
  66698. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  66699. };
  66700. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  66701. // orientation of a polygon is flipped.
  66702. Vertex.prototype.flip = function () {
  66703. this.normal = this.normal.scale(-1);
  66704. };
  66705. // Create a new vertex between this vertex and `other` by linearly
  66706. // interpolating all properties using a parameter of `t`. Subclasses should
  66707. // override this to interpolate additional properties.
  66708. Vertex.prototype.interpolate = function (other, t) {
  66709. 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));
  66710. };
  66711. return Vertex;
  66712. }());
  66713. // # class Plane
  66714. // Represents a plane in 3D space.
  66715. var Plane = /** @class */ (function () {
  66716. function Plane(normal, w) {
  66717. this.normal = normal;
  66718. this.w = w;
  66719. }
  66720. Plane.FromPoints = function (a, b, c) {
  66721. var v0 = c.subtract(a);
  66722. var v1 = b.subtract(a);
  66723. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  66724. return null;
  66725. }
  66726. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  66727. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  66728. };
  66729. Plane.prototype.clone = function () {
  66730. return new Plane(this.normal.clone(), this.w);
  66731. };
  66732. Plane.prototype.flip = function () {
  66733. this.normal.scaleInPlace(-1);
  66734. this.w = -this.w;
  66735. };
  66736. // Split `polygon` by this plane if needed, then put the polygon or polygon
  66737. // fragments in the appropriate lists. Coplanar polygons go into either
  66738. // `coplanarFront` or `coplanarBack` depending on their orientation with
  66739. // respect to this plane. Polygons in front or in back of this plane go into
  66740. // either `front` or `back`.
  66741. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  66742. var COPLANAR = 0;
  66743. var FRONT = 1;
  66744. var BACK = 2;
  66745. var SPANNING = 3;
  66746. // Classify each point as well as the entire polygon into one of the above
  66747. // four classes.
  66748. var polygonType = 0;
  66749. var types = [];
  66750. var i;
  66751. var t;
  66752. for (i = 0; i < polygon.vertices.length; i++) {
  66753. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  66754. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  66755. polygonType |= type;
  66756. types.push(type);
  66757. }
  66758. // Put the polygon in the correct list, splitting it when necessary.
  66759. switch (polygonType) {
  66760. case COPLANAR:
  66761. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  66762. break;
  66763. case FRONT:
  66764. front.push(polygon);
  66765. break;
  66766. case BACK:
  66767. back.push(polygon);
  66768. break;
  66769. case SPANNING:
  66770. var f = [], b = [];
  66771. for (i = 0; i < polygon.vertices.length; i++) {
  66772. var j = (i + 1) % polygon.vertices.length;
  66773. var ti = types[i], tj = types[j];
  66774. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  66775. if (ti !== BACK)
  66776. f.push(vi);
  66777. if (ti !== FRONT)
  66778. b.push(ti !== BACK ? vi.clone() : vi);
  66779. if ((ti | tj) === SPANNING) {
  66780. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  66781. var v = vi.interpolate(vj, t);
  66782. f.push(v);
  66783. b.push(v.clone());
  66784. }
  66785. }
  66786. var poly;
  66787. if (f.length >= 3) {
  66788. poly = new Polygon(f, polygon.shared);
  66789. if (poly.plane)
  66790. front.push(poly);
  66791. }
  66792. if (b.length >= 3) {
  66793. poly = new Polygon(b, polygon.shared);
  66794. if (poly.plane)
  66795. back.push(poly);
  66796. }
  66797. break;
  66798. }
  66799. };
  66800. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  66801. // point is on the plane.
  66802. Plane.EPSILON = 1e-5;
  66803. return Plane;
  66804. }());
  66805. // # class Polygon
  66806. // Represents a convex polygon. The vertices used to initialize a polygon must
  66807. // be coplanar and form a convex loop.
  66808. //
  66809. // Each convex polygon has a `shared` property, which is shared between all
  66810. // polygons that are clones of each other or were split from the same polygon.
  66811. // This can be used to define per-polygon properties (such as surface color).
  66812. var Polygon = /** @class */ (function () {
  66813. function Polygon(vertices, shared) {
  66814. this.vertices = vertices;
  66815. this.shared = shared;
  66816. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  66817. }
  66818. Polygon.prototype.clone = function () {
  66819. var vertices = this.vertices.map(function (v) { return v.clone(); });
  66820. return new Polygon(vertices, this.shared);
  66821. };
  66822. Polygon.prototype.flip = function () {
  66823. this.vertices.reverse().map(function (v) { v.flip(); });
  66824. this.plane.flip();
  66825. };
  66826. return Polygon;
  66827. }());
  66828. // # class Node
  66829. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  66830. // by picking a polygon to split along. That polygon (and all other coplanar
  66831. // polygons) are added directly to that node and the other polygons are added to
  66832. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  66833. // no distinction between internal and leaf nodes.
  66834. var Node = /** @class */ (function () {
  66835. function Node(polygons) {
  66836. this.plane = null;
  66837. this.front = null;
  66838. this.back = null;
  66839. this.polygons = new Array();
  66840. if (polygons) {
  66841. this.build(polygons);
  66842. }
  66843. }
  66844. Node.prototype.clone = function () {
  66845. var node = new Node();
  66846. node.plane = this.plane && this.plane.clone();
  66847. node.front = this.front && this.front.clone();
  66848. node.back = this.back && this.back.clone();
  66849. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  66850. return node;
  66851. };
  66852. // Convert solid space to empty space and empty space to solid space.
  66853. Node.prototype.invert = function () {
  66854. for (var i = 0; i < this.polygons.length; i++) {
  66855. this.polygons[i].flip();
  66856. }
  66857. if (this.plane) {
  66858. this.plane.flip();
  66859. }
  66860. if (this.front) {
  66861. this.front.invert();
  66862. }
  66863. if (this.back) {
  66864. this.back.invert();
  66865. }
  66866. var temp = this.front;
  66867. this.front = this.back;
  66868. this.back = temp;
  66869. };
  66870. // Recursively remove all polygons in `polygons` that are inside this BSP
  66871. // tree.
  66872. Node.prototype.clipPolygons = function (polygons) {
  66873. if (!this.plane)
  66874. return polygons.slice();
  66875. var front = new Array(), back = new Array();
  66876. for (var i = 0; i < polygons.length; i++) {
  66877. this.plane.splitPolygon(polygons[i], front, back, front, back);
  66878. }
  66879. if (this.front) {
  66880. front = this.front.clipPolygons(front);
  66881. }
  66882. if (this.back) {
  66883. back = this.back.clipPolygons(back);
  66884. }
  66885. else {
  66886. back = [];
  66887. }
  66888. return front.concat(back);
  66889. };
  66890. // Remove all polygons in this BSP tree that are inside the other BSP tree
  66891. // `bsp`.
  66892. Node.prototype.clipTo = function (bsp) {
  66893. this.polygons = bsp.clipPolygons(this.polygons);
  66894. if (this.front)
  66895. this.front.clipTo(bsp);
  66896. if (this.back)
  66897. this.back.clipTo(bsp);
  66898. };
  66899. // Return a list of all polygons in this BSP tree.
  66900. Node.prototype.allPolygons = function () {
  66901. var polygons = this.polygons.slice();
  66902. if (this.front)
  66903. polygons = polygons.concat(this.front.allPolygons());
  66904. if (this.back)
  66905. polygons = polygons.concat(this.back.allPolygons());
  66906. return polygons;
  66907. };
  66908. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  66909. // new polygons are filtered down to the bottom of the tree and become new
  66910. // nodes there. Each set of polygons is partitioned using the first polygon
  66911. // (no heuristic is used to pick a good split).
  66912. Node.prototype.build = function (polygons) {
  66913. if (!polygons.length)
  66914. return;
  66915. if (!this.plane)
  66916. this.plane = polygons[0].plane.clone();
  66917. var front = new Array(), back = new Array();
  66918. for (var i = 0; i < polygons.length; i++) {
  66919. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  66920. }
  66921. if (front.length) {
  66922. if (!this.front)
  66923. this.front = new Node();
  66924. this.front.build(front);
  66925. }
  66926. if (back.length) {
  66927. if (!this.back)
  66928. this.back = new Node();
  66929. this.back.build(back);
  66930. }
  66931. };
  66932. return Node;
  66933. }());
  66934. var CSG = /** @class */ (function () {
  66935. function CSG() {
  66936. this.polygons = new Array();
  66937. }
  66938. // Convert BABYLON.Mesh to BABYLON.CSG
  66939. CSG.FromMesh = function (mesh) {
  66940. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  66941. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  66942. if (mesh instanceof BABYLON.Mesh) {
  66943. mesh.computeWorldMatrix(true);
  66944. matrix = mesh.getWorldMatrix();
  66945. meshPosition = mesh.position.clone();
  66946. meshRotation = mesh.rotation.clone();
  66947. if (mesh.rotationQuaternion) {
  66948. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  66949. }
  66950. meshScaling = mesh.scaling.clone();
  66951. }
  66952. else {
  66953. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  66954. }
  66955. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66956. var subMeshes = mesh.subMeshes;
  66957. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  66958. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  66959. vertices = [];
  66960. for (var j = 0; j < 3; j++) {
  66961. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  66962. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  66963. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  66964. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  66965. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  66966. vertex = new Vertex(position, normal, uv);
  66967. vertices.push(vertex);
  66968. }
  66969. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  66970. // To handle the case of degenerated triangle
  66971. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  66972. if (polygon.plane)
  66973. polygons.push(polygon);
  66974. }
  66975. }
  66976. var csg = CSG.FromPolygons(polygons);
  66977. csg.matrix = matrix;
  66978. csg.position = meshPosition;
  66979. csg.rotation = meshRotation;
  66980. csg.scaling = meshScaling;
  66981. csg.rotationQuaternion = meshRotationQuaternion;
  66982. currentCSGMeshId++;
  66983. return csg;
  66984. };
  66985. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  66986. CSG.FromPolygons = function (polygons) {
  66987. var csg = new CSG();
  66988. csg.polygons = polygons;
  66989. return csg;
  66990. };
  66991. CSG.prototype.clone = function () {
  66992. var csg = new CSG();
  66993. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  66994. csg.copyTransformAttributes(this);
  66995. return csg;
  66996. };
  66997. CSG.prototype.union = function (csg) {
  66998. var a = new Node(this.clone().polygons);
  66999. var b = new Node(csg.clone().polygons);
  67000. a.clipTo(b);
  67001. b.clipTo(a);
  67002. b.invert();
  67003. b.clipTo(a);
  67004. b.invert();
  67005. a.build(b.allPolygons());
  67006. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67007. };
  67008. CSG.prototype.unionInPlace = function (csg) {
  67009. var a = new Node(this.polygons);
  67010. var b = new Node(csg.polygons);
  67011. a.clipTo(b);
  67012. b.clipTo(a);
  67013. b.invert();
  67014. b.clipTo(a);
  67015. b.invert();
  67016. a.build(b.allPolygons());
  67017. this.polygons = a.allPolygons();
  67018. };
  67019. CSG.prototype.subtract = function (csg) {
  67020. var a = new Node(this.clone().polygons);
  67021. var b = new Node(csg.clone().polygons);
  67022. a.invert();
  67023. a.clipTo(b);
  67024. b.clipTo(a);
  67025. b.invert();
  67026. b.clipTo(a);
  67027. b.invert();
  67028. a.build(b.allPolygons());
  67029. a.invert();
  67030. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67031. };
  67032. CSG.prototype.subtractInPlace = function (csg) {
  67033. var a = new Node(this.polygons);
  67034. var b = new Node(csg.polygons);
  67035. a.invert();
  67036. a.clipTo(b);
  67037. b.clipTo(a);
  67038. b.invert();
  67039. b.clipTo(a);
  67040. b.invert();
  67041. a.build(b.allPolygons());
  67042. a.invert();
  67043. this.polygons = a.allPolygons();
  67044. };
  67045. CSG.prototype.intersect = function (csg) {
  67046. var a = new Node(this.clone().polygons);
  67047. var b = new Node(csg.clone().polygons);
  67048. a.invert();
  67049. b.clipTo(a);
  67050. b.invert();
  67051. a.clipTo(b);
  67052. b.clipTo(a);
  67053. a.build(b.allPolygons());
  67054. a.invert();
  67055. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67056. };
  67057. CSG.prototype.intersectInPlace = function (csg) {
  67058. var a = new Node(this.polygons);
  67059. var b = new Node(csg.polygons);
  67060. a.invert();
  67061. b.clipTo(a);
  67062. b.invert();
  67063. a.clipTo(b);
  67064. b.clipTo(a);
  67065. a.build(b.allPolygons());
  67066. a.invert();
  67067. this.polygons = a.allPolygons();
  67068. };
  67069. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67070. // not modified.
  67071. CSG.prototype.inverse = function () {
  67072. var csg = this.clone();
  67073. csg.inverseInPlace();
  67074. return csg;
  67075. };
  67076. CSG.prototype.inverseInPlace = function () {
  67077. this.polygons.map(function (p) { p.flip(); });
  67078. };
  67079. // This is used to keep meshes transformations so they can be restored
  67080. // when we build back a Babylon Mesh
  67081. // NB : All CSG operations are performed in world coordinates
  67082. CSG.prototype.copyTransformAttributes = function (csg) {
  67083. this.matrix = csg.matrix;
  67084. this.position = csg.position;
  67085. this.rotation = csg.rotation;
  67086. this.scaling = csg.scaling;
  67087. this.rotationQuaternion = csg.rotationQuaternion;
  67088. return this;
  67089. };
  67090. // Build Raw mesh from CSG
  67091. // Coordinates here are in world space
  67092. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67093. var matrix = this.matrix.clone();
  67094. matrix.invert();
  67095. 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;
  67096. if (keepSubMeshes) {
  67097. // Sort Polygons, since subMeshes are indices range
  67098. polygons.sort(function (a, b) {
  67099. if (a.shared.meshId === b.shared.meshId) {
  67100. return a.shared.subMeshId - b.shared.subMeshId;
  67101. }
  67102. else {
  67103. return a.shared.meshId - b.shared.meshId;
  67104. }
  67105. });
  67106. }
  67107. for (var i = 0, il = polygons.length; i < il; i++) {
  67108. polygon = polygons[i];
  67109. // Building SubMeshes
  67110. if (!subMesh_dict[polygon.shared.meshId]) {
  67111. subMesh_dict[polygon.shared.meshId] = {};
  67112. }
  67113. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67114. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67115. indexStart: +Infinity,
  67116. indexEnd: -Infinity,
  67117. materialIndex: polygon.shared.materialIndex
  67118. };
  67119. }
  67120. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67121. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67122. polygonIndices[0] = 0;
  67123. polygonIndices[1] = j - 1;
  67124. polygonIndices[2] = j;
  67125. for (var k = 0; k < 3; k++) {
  67126. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67127. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67128. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67129. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67130. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67131. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67132. // Check if 2 points can be merged
  67133. if (!(typeof vertex_idx !== 'undefined' &&
  67134. normals[vertex_idx * 3] === localNormal.x &&
  67135. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67136. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67137. uvs[vertex_idx * 2] === uv.x &&
  67138. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67139. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67140. uvs.push(uv.x, uv.y);
  67141. normals.push(normal.x, normal.y, normal.z);
  67142. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67143. }
  67144. indices.push(vertex_idx);
  67145. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67146. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67147. currentIndex++;
  67148. }
  67149. }
  67150. }
  67151. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67152. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67153. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67154. mesh.setIndices(indices, null);
  67155. if (keepSubMeshes) {
  67156. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67157. var materialIndexOffset = 0, materialMaxIndex;
  67158. mesh.subMeshes = new Array();
  67159. for (var m in subMesh_dict) {
  67160. materialMaxIndex = -1;
  67161. for (var sm in subMesh_dict[m]) {
  67162. subMesh_obj = subMesh_dict[m][sm];
  67163. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67164. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67165. }
  67166. materialIndexOffset += ++materialMaxIndex;
  67167. }
  67168. }
  67169. return mesh;
  67170. };
  67171. // Build Mesh from CSG taking material and transforms into account
  67172. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67173. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67174. mesh.material = material;
  67175. mesh.position.copyFrom(this.position);
  67176. mesh.rotation.copyFrom(this.rotation);
  67177. if (this.rotationQuaternion) {
  67178. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67179. }
  67180. mesh.scaling.copyFrom(this.scaling);
  67181. mesh.computeWorldMatrix(true);
  67182. return mesh;
  67183. };
  67184. return CSG;
  67185. }());
  67186. BABYLON.CSG = CSG;
  67187. })(BABYLON || (BABYLON = {}));
  67188. //# sourceMappingURL=babylon.csg.js.map
  67189. var BABYLON;
  67190. (function (BABYLON) {
  67191. var LensFlare = /** @class */ (function () {
  67192. function LensFlare(size, position, color, imgUrl, system) {
  67193. this.size = size;
  67194. this.position = position;
  67195. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67196. this.color = color || new BABYLON.Color3(1, 1, 1);
  67197. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67198. this._system = system;
  67199. system.lensFlares.push(this);
  67200. }
  67201. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67202. return new LensFlare(size, position, color, imgUrl, system);
  67203. };
  67204. LensFlare.prototype.dispose = function () {
  67205. if (this.texture) {
  67206. this.texture.dispose();
  67207. }
  67208. // Remove from scene
  67209. var index = this._system.lensFlares.indexOf(this);
  67210. this._system.lensFlares.splice(index, 1);
  67211. };
  67212. ;
  67213. return LensFlare;
  67214. }());
  67215. BABYLON.LensFlare = LensFlare;
  67216. })(BABYLON || (BABYLON = {}));
  67217. //# sourceMappingURL=babylon.lensFlare.js.map
  67218. var BABYLON;
  67219. (function (BABYLON) {
  67220. var LensFlareSystem = /** @class */ (function () {
  67221. function LensFlareSystem(name, emitter, scene) {
  67222. this.name = name;
  67223. this.lensFlares = new Array();
  67224. this.borderLimit = 300;
  67225. this.viewportBorder = 0;
  67226. this.layerMask = 0x0FFFFFFF;
  67227. this._vertexBuffers = {};
  67228. this._isEnabled = true;
  67229. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67230. this._emitter = emitter;
  67231. this.id = name;
  67232. scene.lensFlareSystems.push(this);
  67233. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67234. var engine = scene.getEngine();
  67235. // VBO
  67236. var vertices = [];
  67237. vertices.push(1, 1);
  67238. vertices.push(-1, 1);
  67239. vertices.push(-1, -1);
  67240. vertices.push(1, -1);
  67241. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67242. // Indices
  67243. var indices = [];
  67244. indices.push(0);
  67245. indices.push(1);
  67246. indices.push(2);
  67247. indices.push(0);
  67248. indices.push(2);
  67249. indices.push(3);
  67250. this._indexBuffer = engine.createIndexBuffer(indices);
  67251. // Effects
  67252. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67253. }
  67254. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67255. get: function () {
  67256. return this._isEnabled;
  67257. },
  67258. set: function (value) {
  67259. this._isEnabled = value;
  67260. },
  67261. enumerable: true,
  67262. configurable: true
  67263. });
  67264. LensFlareSystem.prototype.getScene = function () {
  67265. return this._scene;
  67266. };
  67267. LensFlareSystem.prototype.getEmitter = function () {
  67268. return this._emitter;
  67269. };
  67270. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67271. this._emitter = newEmitter;
  67272. };
  67273. LensFlareSystem.prototype.getEmitterPosition = function () {
  67274. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67275. };
  67276. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67277. var position = this.getEmitterPosition();
  67278. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67279. this._positionX = position.x;
  67280. this._positionY = position.y;
  67281. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67282. if (this.viewportBorder > 0) {
  67283. globalViewport.x -= this.viewportBorder;
  67284. globalViewport.y -= this.viewportBorder;
  67285. globalViewport.width += this.viewportBorder * 2;
  67286. globalViewport.height += this.viewportBorder * 2;
  67287. position.x += this.viewportBorder;
  67288. position.y += this.viewportBorder;
  67289. this._positionX += this.viewportBorder;
  67290. this._positionY += this.viewportBorder;
  67291. }
  67292. if (position.z > 0) {
  67293. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67294. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67295. return true;
  67296. }
  67297. return true;
  67298. }
  67299. return false;
  67300. };
  67301. LensFlareSystem.prototype._isVisible = function () {
  67302. if (!this._isEnabled || !this._scene.activeCamera) {
  67303. return false;
  67304. }
  67305. var emitterPosition = this.getEmitterPosition();
  67306. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67307. var distance = direction.length();
  67308. direction.normalize();
  67309. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67310. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67311. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67312. };
  67313. LensFlareSystem.prototype.render = function () {
  67314. if (!this._effect.isReady() || !this._scene.activeCamera)
  67315. return false;
  67316. var engine = this._scene.getEngine();
  67317. var viewport = this._scene.activeCamera.viewport;
  67318. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67319. // Position
  67320. if (!this.computeEffectivePosition(globalViewport)) {
  67321. return false;
  67322. }
  67323. // Visibility
  67324. if (!this._isVisible()) {
  67325. return false;
  67326. }
  67327. // Intensity
  67328. var awayX;
  67329. var awayY;
  67330. if (this._positionX < this.borderLimit + globalViewport.x) {
  67331. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67332. }
  67333. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67334. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67335. }
  67336. else {
  67337. awayX = 0;
  67338. }
  67339. if (this._positionY < this.borderLimit + globalViewport.y) {
  67340. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67341. }
  67342. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67343. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67344. }
  67345. else {
  67346. awayY = 0;
  67347. }
  67348. var away = (awayX > awayY) ? awayX : awayY;
  67349. away -= this.viewportBorder;
  67350. if (away > this.borderLimit) {
  67351. away = this.borderLimit;
  67352. }
  67353. var intensity = 1.0 - (away / this.borderLimit);
  67354. if (intensity < 0) {
  67355. return false;
  67356. }
  67357. if (intensity > 1.0) {
  67358. intensity = 1.0;
  67359. }
  67360. if (this.viewportBorder > 0) {
  67361. globalViewport.x += this.viewportBorder;
  67362. globalViewport.y += this.viewportBorder;
  67363. globalViewport.width -= this.viewportBorder * 2;
  67364. globalViewport.height -= this.viewportBorder * 2;
  67365. this._positionX -= this.viewportBorder;
  67366. this._positionY -= this.viewportBorder;
  67367. }
  67368. // Position
  67369. var centerX = globalViewport.x + globalViewport.width / 2;
  67370. var centerY = globalViewport.y + globalViewport.height / 2;
  67371. var distX = centerX - this._positionX;
  67372. var distY = centerY - this._positionY;
  67373. // Effects
  67374. engine.enableEffect(this._effect);
  67375. engine.setState(false);
  67376. engine.setDepthBuffer(false);
  67377. // VBOs
  67378. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67379. // Flares
  67380. for (var index = 0; index < this.lensFlares.length; index++) {
  67381. var flare = this.lensFlares[index];
  67382. engine.setAlphaMode(flare.alphaMode);
  67383. var x = centerX - (distX * flare.position);
  67384. var y = centerY - (distY * flare.position);
  67385. var cw = flare.size;
  67386. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67387. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67388. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67389. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67390. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67391. // Texture
  67392. this._effect.setTexture("textureSampler", flare.texture);
  67393. // Color
  67394. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67395. // Draw order
  67396. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67397. }
  67398. engine.setDepthBuffer(true);
  67399. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67400. return true;
  67401. };
  67402. LensFlareSystem.prototype.dispose = function () {
  67403. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67404. if (vertexBuffer) {
  67405. vertexBuffer.dispose();
  67406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67407. }
  67408. if (this._indexBuffer) {
  67409. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67410. this._indexBuffer = null;
  67411. }
  67412. while (this.lensFlares.length) {
  67413. this.lensFlares[0].dispose();
  67414. }
  67415. // Remove from scene
  67416. var index = this._scene.lensFlareSystems.indexOf(this);
  67417. this._scene.lensFlareSystems.splice(index, 1);
  67418. };
  67419. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67420. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67421. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67422. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67423. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67424. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67425. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67426. var parsedFlare = parsedLensFlareSystem.flares[index];
  67427. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67428. }
  67429. return lensFlareSystem;
  67430. };
  67431. LensFlareSystem.prototype.serialize = function () {
  67432. var serializationObject = {};
  67433. serializationObject.id = this.id;
  67434. serializationObject.name = this.name;
  67435. serializationObject.emitterId = this.getEmitter().id;
  67436. serializationObject.borderLimit = this.borderLimit;
  67437. serializationObject.flares = [];
  67438. for (var index = 0; index < this.lensFlares.length; index++) {
  67439. var flare = this.lensFlares[index];
  67440. serializationObject.flares.push({
  67441. size: flare.size,
  67442. position: flare.position,
  67443. color: flare.color.asArray(),
  67444. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67445. });
  67446. }
  67447. return serializationObject;
  67448. };
  67449. return LensFlareSystem;
  67450. }());
  67451. BABYLON.LensFlareSystem = LensFlareSystem;
  67452. })(BABYLON || (BABYLON = {}));
  67453. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67454. var BABYLON;
  67455. (function (BABYLON) {
  67456. /**
  67457. * This is a holder class for the physics joint created by the physics plugin.
  67458. * It holds a set of functions to control the underlying joint.
  67459. */
  67460. var PhysicsJoint = /** @class */ (function () {
  67461. function PhysicsJoint(type, jointData) {
  67462. this.type = type;
  67463. this.jointData = jointData;
  67464. jointData.nativeParams = jointData.nativeParams || {};
  67465. }
  67466. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67467. get: function () {
  67468. return this._physicsJoint;
  67469. },
  67470. set: function (newJoint) {
  67471. if (this._physicsJoint) {
  67472. //remove from the wolrd
  67473. }
  67474. this._physicsJoint = newJoint;
  67475. },
  67476. enumerable: true,
  67477. configurable: true
  67478. });
  67479. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67480. set: function (physicsPlugin) {
  67481. this._physicsPlugin = physicsPlugin;
  67482. },
  67483. enumerable: true,
  67484. configurable: true
  67485. });
  67486. /**
  67487. * Execute a function that is physics-plugin specific.
  67488. * @param {Function} func the function that will be executed.
  67489. * It accepts two parameters: the physics world and the physics joint.
  67490. */
  67491. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67492. func(this._physicsPlugin.world, this._physicsJoint);
  67493. };
  67494. //TODO check if the native joints are the same
  67495. //Joint Types
  67496. PhysicsJoint.DistanceJoint = 0;
  67497. PhysicsJoint.HingeJoint = 1;
  67498. PhysicsJoint.BallAndSocketJoint = 2;
  67499. PhysicsJoint.WheelJoint = 3;
  67500. PhysicsJoint.SliderJoint = 4;
  67501. //OIMO
  67502. PhysicsJoint.PrismaticJoint = 5;
  67503. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67504. PhysicsJoint.UniversalJoint = 6;
  67505. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67506. //Cannon
  67507. //Similar to a Ball-Joint. Different in params
  67508. PhysicsJoint.PointToPointJoint = 8;
  67509. //Cannon only at the moment
  67510. PhysicsJoint.SpringJoint = 9;
  67511. PhysicsJoint.LockJoint = 10;
  67512. return PhysicsJoint;
  67513. }());
  67514. BABYLON.PhysicsJoint = PhysicsJoint;
  67515. /**
  67516. * A class representing a physics distance joint.
  67517. */
  67518. var DistanceJoint = /** @class */ (function (_super) {
  67519. __extends(DistanceJoint, _super);
  67520. function DistanceJoint(jointData) {
  67521. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67522. }
  67523. /**
  67524. * Update the predefined distance.
  67525. */
  67526. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67527. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67528. };
  67529. return DistanceJoint;
  67530. }(PhysicsJoint));
  67531. BABYLON.DistanceJoint = DistanceJoint;
  67532. var MotorEnabledJoint = /** @class */ (function (_super) {
  67533. __extends(MotorEnabledJoint, _super);
  67534. function MotorEnabledJoint(type, jointData) {
  67535. return _super.call(this, type, jointData) || this;
  67536. }
  67537. /**
  67538. * Set the motor values.
  67539. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67540. * @param {number} force the force to apply
  67541. * @param {number} maxForce max force for this motor.
  67542. */
  67543. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67544. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67545. };
  67546. /**
  67547. * Set the motor's limits.
  67548. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67549. */
  67550. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67551. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67552. };
  67553. return MotorEnabledJoint;
  67554. }(PhysicsJoint));
  67555. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67556. /**
  67557. * This class represents a single hinge physics joint
  67558. */
  67559. var HingeJoint = /** @class */ (function (_super) {
  67560. __extends(HingeJoint, _super);
  67561. function HingeJoint(jointData) {
  67562. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67563. }
  67564. /**
  67565. * Set the motor values.
  67566. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67567. * @param {number} force the force to apply
  67568. * @param {number} maxForce max force for this motor.
  67569. */
  67570. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67571. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67572. };
  67573. /**
  67574. * Set the motor's limits.
  67575. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67576. */
  67577. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67578. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67579. };
  67580. return HingeJoint;
  67581. }(MotorEnabledJoint));
  67582. BABYLON.HingeJoint = HingeJoint;
  67583. /**
  67584. * This class represents a dual hinge physics joint (same as wheel joint)
  67585. */
  67586. var Hinge2Joint = /** @class */ (function (_super) {
  67587. __extends(Hinge2Joint, _super);
  67588. function Hinge2Joint(jointData) {
  67589. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67590. }
  67591. /**
  67592. * Set the motor values.
  67593. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67594. * @param {number} force the force to apply
  67595. * @param {number} maxForce max force for this motor.
  67596. * @param {motorIndex} the motor's index, 0 or 1.
  67597. */
  67598. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67599. if (motorIndex === void 0) { motorIndex = 0; }
  67600. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67601. };
  67602. /**
  67603. * Set the motor limits.
  67604. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67605. * @param {number} upperLimit the upper limit
  67606. * @param {number} lowerLimit lower limit
  67607. * @param {motorIndex} the motor's index, 0 or 1.
  67608. */
  67609. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67610. if (motorIndex === void 0) { motorIndex = 0; }
  67611. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67612. };
  67613. return Hinge2Joint;
  67614. }(MotorEnabledJoint));
  67615. BABYLON.Hinge2Joint = Hinge2Joint;
  67616. })(BABYLON || (BABYLON = {}));
  67617. //# sourceMappingURL=babylon.physicsJoint.js.map
  67618. var BABYLON;
  67619. (function (BABYLON) {
  67620. var PhysicsImpostor = /** @class */ (function () {
  67621. function PhysicsImpostor(object, type, _options, _scene) {
  67622. if (_options === void 0) { _options = { mass: 0 }; }
  67623. var _this = this;
  67624. this.object = object;
  67625. this.type = type;
  67626. this._options = _options;
  67627. this._scene = _scene;
  67628. this._bodyUpdateRequired = false;
  67629. this._onBeforePhysicsStepCallbacks = new Array();
  67630. this._onAfterPhysicsStepCallbacks = new Array();
  67631. this._onPhysicsCollideCallbacks = [];
  67632. this._deltaPosition = BABYLON.Vector3.Zero();
  67633. this._isDisposed = false;
  67634. //temp variables for parent rotation calculations
  67635. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67636. this._tmpQuat = new BABYLON.Quaternion();
  67637. this._tmpQuat2 = new BABYLON.Quaternion();
  67638. /**
  67639. * this function is executed by the physics engine.
  67640. */
  67641. this.beforeStep = function () {
  67642. if (!_this._physicsEngine) {
  67643. return;
  67644. }
  67645. _this.object.translate(_this._deltaPosition, -1);
  67646. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67647. _this.object.computeWorldMatrix(false);
  67648. if (_this.object.parent && _this.object.rotationQuaternion) {
  67649. _this.getParentsRotation();
  67650. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67651. }
  67652. else {
  67653. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67654. }
  67655. if (!_this._options.disableBidirectionalTransformation) {
  67656. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67657. }
  67658. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67659. func(_this);
  67660. });
  67661. };
  67662. /**
  67663. * this function is executed by the physics engine.
  67664. */
  67665. this.afterStep = function () {
  67666. if (!_this._physicsEngine) {
  67667. return;
  67668. }
  67669. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67670. func(_this);
  67671. });
  67672. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67673. // object has now its world rotation. needs to be converted to local.
  67674. if (_this.object.parent && _this.object.rotationQuaternion) {
  67675. _this.getParentsRotation();
  67676. _this._tmpQuat.conjugateInPlace();
  67677. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67678. }
  67679. // take the position set and make it the absolute position of this object.
  67680. _this.object.setAbsolutePosition(_this.object.position);
  67681. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67682. _this.object.translate(_this._deltaPosition, 1);
  67683. };
  67684. /**
  67685. * Legacy collision detection event support
  67686. */
  67687. this.onCollideEvent = null;
  67688. //event and body object due to cannon's event-based architecture.
  67689. this.onCollide = function (e) {
  67690. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67691. return;
  67692. }
  67693. if (!_this._physicsEngine) {
  67694. return;
  67695. }
  67696. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  67697. if (otherImpostor) {
  67698. // Legacy collision detection event support
  67699. if (_this.onCollideEvent) {
  67700. _this.onCollideEvent(_this, otherImpostor);
  67701. }
  67702. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  67703. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  67704. }).forEach(function (obj) {
  67705. obj.callback(_this, otherImpostor);
  67706. });
  67707. }
  67708. };
  67709. //sanity check!
  67710. if (!this.object) {
  67711. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  67712. return;
  67713. }
  67714. //legacy support for old syntax.
  67715. if (!this._scene && object.getScene) {
  67716. this._scene = object.getScene();
  67717. }
  67718. if (!this._scene) {
  67719. return;
  67720. }
  67721. this._physicsEngine = this._scene.getPhysicsEngine();
  67722. if (!this._physicsEngine) {
  67723. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  67724. }
  67725. else {
  67726. //set the object's quaternion, if not set
  67727. if (!this.object.rotationQuaternion) {
  67728. if (this.object.rotation) {
  67729. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  67730. }
  67731. else {
  67732. this.object.rotationQuaternion = new BABYLON.Quaternion();
  67733. }
  67734. }
  67735. //default options params
  67736. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  67737. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  67738. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  67739. this._joints = [];
  67740. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  67741. if (!this.object.parent || this._options.ignoreParent) {
  67742. this._init();
  67743. }
  67744. else if (this.object.parent.physicsImpostor) {
  67745. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  67746. }
  67747. }
  67748. }
  67749. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  67750. get: function () {
  67751. return this._isDisposed;
  67752. },
  67753. enumerable: true,
  67754. configurable: true
  67755. });
  67756. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  67757. get: function () {
  67758. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  67759. },
  67760. set: function (value) {
  67761. this.setMass(value);
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  67767. get: function () {
  67768. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  67769. },
  67770. set: function (value) {
  67771. if (!this._physicsEngine) {
  67772. return;
  67773. }
  67774. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  67775. },
  67776. enumerable: true,
  67777. configurable: true
  67778. });
  67779. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  67780. get: function () {
  67781. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  67782. },
  67783. set: function (value) {
  67784. if (!this._physicsEngine) {
  67785. return;
  67786. }
  67787. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  67788. },
  67789. enumerable: true,
  67790. configurable: true
  67791. });
  67792. /**
  67793. * This function will completly initialize this impostor.
  67794. * It will create a new body - but only if this mesh has no parent.
  67795. * If it has, this impostor will not be used other than to define the impostor
  67796. * of the child mesh.
  67797. */
  67798. PhysicsImpostor.prototype._init = function () {
  67799. if (!this._physicsEngine) {
  67800. return;
  67801. }
  67802. this._physicsEngine.removeImpostor(this);
  67803. this.physicsBody = null;
  67804. this._parent = this._parent || this._getPhysicsParent();
  67805. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  67806. this._physicsEngine.addImpostor(this);
  67807. }
  67808. };
  67809. PhysicsImpostor.prototype._getPhysicsParent = function () {
  67810. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  67811. var parentMesh = this.object.parent;
  67812. return parentMesh.physicsImpostor;
  67813. }
  67814. return null;
  67815. };
  67816. /**
  67817. * Should a new body be generated.
  67818. */
  67819. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  67820. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  67821. };
  67822. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  67823. this.forceUpdate();
  67824. };
  67825. /**
  67826. * Force a regeneration of this or the parent's impostor's body.
  67827. * Use under cautious - This will remove all joints already implemented.
  67828. */
  67829. PhysicsImpostor.prototype.forceUpdate = function () {
  67830. this._init();
  67831. if (this.parent && !this._options.ignoreParent) {
  67832. this.parent.forceUpdate();
  67833. }
  67834. };
  67835. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  67836. /*public get mesh(): AbstractMesh {
  67837. return this._mesh;
  67838. }*/
  67839. /**
  67840. * Gets the body that holds this impostor. Either its own, or its parent.
  67841. */
  67842. get: function () {
  67843. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  67844. },
  67845. /**
  67846. * Set the physics body. Used mainly by the physics engine/plugin
  67847. */
  67848. set: function (physicsBody) {
  67849. if (this._physicsBody && this._physicsEngine) {
  67850. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  67851. }
  67852. this._physicsBody = physicsBody;
  67853. this.resetUpdateFlags();
  67854. },
  67855. enumerable: true,
  67856. configurable: true
  67857. });
  67858. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  67859. get: function () {
  67860. return !this._options.ignoreParent && this._parent ? this._parent : null;
  67861. },
  67862. set: function (value) {
  67863. this._parent = value;
  67864. },
  67865. enumerable: true,
  67866. configurable: true
  67867. });
  67868. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  67869. this._bodyUpdateRequired = false;
  67870. };
  67871. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  67872. if (this.object.getBoundingInfo) {
  67873. var q = this.object.rotationQuaternion;
  67874. //reset rotation
  67875. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  67876. //calculate the world matrix with no rotation
  67877. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67878. var boundingInfo = this.object.getBoundingInfo();
  67879. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  67880. //bring back the rotation
  67881. this.object.rotationQuaternion = q;
  67882. //calculate the world matrix with the new rotation
  67883. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67884. return size;
  67885. }
  67886. else {
  67887. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  67888. }
  67889. };
  67890. PhysicsImpostor.prototype.getObjectCenter = function () {
  67891. if (this.object.getBoundingInfo) {
  67892. var boundingInfo = this.object.getBoundingInfo();
  67893. return boundingInfo.boundingBox.centerWorld;
  67894. }
  67895. else {
  67896. return this.object.position;
  67897. }
  67898. };
  67899. /**
  67900. * Get a specific parametes from the options parameter.
  67901. */
  67902. PhysicsImpostor.prototype.getParam = function (paramName) {
  67903. return this._options[paramName];
  67904. };
  67905. /**
  67906. * Sets a specific parameter in the options given to the physics plugin
  67907. */
  67908. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  67909. this._options[paramName] = value;
  67910. this._bodyUpdateRequired = true;
  67911. };
  67912. /**
  67913. * Specifically change the body's mass option. Won't recreate the physics body object
  67914. */
  67915. PhysicsImpostor.prototype.setMass = function (mass) {
  67916. if (this.getParam("mass") !== mass) {
  67917. this.setParam("mass", mass);
  67918. }
  67919. if (this._physicsEngine) {
  67920. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  67921. }
  67922. };
  67923. PhysicsImpostor.prototype.getLinearVelocity = function () {
  67924. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  67925. };
  67926. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  67927. if (this._physicsEngine) {
  67928. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  67929. }
  67930. };
  67931. PhysicsImpostor.prototype.getAngularVelocity = function () {
  67932. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  67933. };
  67934. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  67935. if (this._physicsEngine) {
  67936. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  67937. }
  67938. };
  67939. /**
  67940. * Execute a function with the physics plugin native code.
  67941. * Provide a function the will have two variables - the world object and the physics body object.
  67942. */
  67943. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  67944. if (this._physicsEngine) {
  67945. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  67946. }
  67947. };
  67948. /**
  67949. * Register a function that will be executed before the physics world is stepping forward.
  67950. */
  67951. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  67952. this._onBeforePhysicsStepCallbacks.push(func);
  67953. };
  67954. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  67955. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  67956. if (index > -1) {
  67957. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  67958. }
  67959. else {
  67960. BABYLON.Tools.Warn("Function to remove was not found");
  67961. }
  67962. };
  67963. /**
  67964. * Register a function that will be executed after the physics step
  67965. */
  67966. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  67967. this._onAfterPhysicsStepCallbacks.push(func);
  67968. };
  67969. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  67970. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  67971. if (index > -1) {
  67972. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  67973. }
  67974. else {
  67975. BABYLON.Tools.Warn("Function to remove was not found");
  67976. }
  67977. };
  67978. /**
  67979. * register a function that will be executed when this impostor collides against a different body.
  67980. */
  67981. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  67982. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67983. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  67984. };
  67985. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  67986. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67987. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  67988. if (index > -1) {
  67989. this._onPhysicsCollideCallbacks.splice(index, 1);
  67990. }
  67991. else {
  67992. BABYLON.Tools.Warn("Function to remove was not found");
  67993. }
  67994. };
  67995. PhysicsImpostor.prototype.getParentsRotation = function () {
  67996. var parent = this.object.parent;
  67997. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  67998. while (parent) {
  67999. if (parent.rotationQuaternion) {
  68000. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68001. }
  68002. else {
  68003. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68004. }
  68005. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68006. parent = parent.parent;
  68007. }
  68008. return this._tmpQuat;
  68009. };
  68010. /**
  68011. * Apply a force
  68012. */
  68013. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68014. if (this._physicsEngine) {
  68015. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68016. }
  68017. return this;
  68018. };
  68019. /**
  68020. * Apply an impulse
  68021. */
  68022. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68023. if (this._physicsEngine) {
  68024. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68025. }
  68026. return this;
  68027. };
  68028. /**
  68029. * A help function to create a joint.
  68030. */
  68031. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68032. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68033. this.addJoint(otherImpostor, joint);
  68034. return this;
  68035. };
  68036. /**
  68037. * Add a joint to this impostor with a different impostor.
  68038. */
  68039. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68040. this._joints.push({
  68041. otherImpostor: otherImpostor,
  68042. joint: joint
  68043. });
  68044. if (this._physicsEngine) {
  68045. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68046. }
  68047. return this;
  68048. };
  68049. /**
  68050. * Will keep this body still, in a sleep mode.
  68051. */
  68052. PhysicsImpostor.prototype.sleep = function () {
  68053. if (this._physicsEngine) {
  68054. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68055. }
  68056. return this;
  68057. };
  68058. /**
  68059. * Wake the body up.
  68060. */
  68061. PhysicsImpostor.prototype.wakeUp = function () {
  68062. if (this._physicsEngine) {
  68063. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68064. }
  68065. return this;
  68066. };
  68067. PhysicsImpostor.prototype.clone = function (newObject) {
  68068. if (!newObject)
  68069. return null;
  68070. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68071. };
  68072. PhysicsImpostor.prototype.dispose = function () {
  68073. var _this = this;
  68074. //no dispose if no physics engine is available.
  68075. if (!this._physicsEngine) {
  68076. return;
  68077. }
  68078. this._joints.forEach(function (j) {
  68079. if (_this._physicsEngine) {
  68080. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68081. }
  68082. });
  68083. //dispose the physics body
  68084. this._physicsEngine.removeImpostor(this);
  68085. if (this.parent) {
  68086. this.parent.forceUpdate();
  68087. }
  68088. else {
  68089. /*this._object.getChildMeshes().forEach(function(mesh) {
  68090. if (mesh.physicsImpostor) {
  68091. if (disposeChildren) {
  68092. mesh.physicsImpostor.dispose();
  68093. mesh.physicsImpostor = null;
  68094. }
  68095. }
  68096. })*/
  68097. }
  68098. this._isDisposed = true;
  68099. };
  68100. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68101. this._deltaPosition.copyFrom(position);
  68102. };
  68103. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68104. if (!this._deltaRotation) {
  68105. this._deltaRotation = new BABYLON.Quaternion();
  68106. }
  68107. this._deltaRotation.copyFrom(rotation);
  68108. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68109. };
  68110. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68111. if (this._physicsEngine) {
  68112. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68113. }
  68114. return this;
  68115. };
  68116. PhysicsImpostor.prototype.getRadius = function () {
  68117. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68118. };
  68119. /**
  68120. * Sync a bone with this impostor
  68121. * @param bone The bone to sync to the impostor.
  68122. * @param boneMesh The mesh that the bone is influencing.
  68123. * @param jointPivot The pivot of the joint / bone in local space.
  68124. * @param distToJoint Optional distance from the impostor to the joint.
  68125. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68126. */
  68127. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68128. var tempVec = PhysicsImpostor._tmpVecs[0];
  68129. var mesh = this.object;
  68130. if (mesh.rotationQuaternion) {
  68131. if (adjustRotation) {
  68132. var tempQuat = PhysicsImpostor._tmpQuat;
  68133. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68134. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68135. }
  68136. else {
  68137. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68138. }
  68139. }
  68140. tempVec.x = 0;
  68141. tempVec.y = 0;
  68142. tempVec.z = 0;
  68143. if (jointPivot) {
  68144. tempVec.x = jointPivot.x;
  68145. tempVec.y = jointPivot.y;
  68146. tempVec.z = jointPivot.z;
  68147. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68148. if (distToJoint === undefined || distToJoint === null) {
  68149. distToJoint = jointPivot.length();
  68150. }
  68151. tempVec.x *= distToJoint;
  68152. tempVec.y *= distToJoint;
  68153. tempVec.z *= distToJoint;
  68154. }
  68155. if (bone.getParent()) {
  68156. tempVec.addInPlace(mesh.getAbsolutePosition());
  68157. bone.setAbsolutePosition(tempVec, boneMesh);
  68158. }
  68159. else {
  68160. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68161. boneMesh.position.x -= tempVec.x;
  68162. boneMesh.position.y -= tempVec.y;
  68163. boneMesh.position.z -= tempVec.z;
  68164. }
  68165. };
  68166. /**
  68167. * Sync impostor to a bone
  68168. * @param bone The bone that the impostor will be synced to.
  68169. * @param boneMesh The mesh that the bone is influencing.
  68170. * @param jointPivot The pivot of the joint / bone in local space.
  68171. * @param distToJoint Optional distance from the impostor to the joint.
  68172. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68173. * @param boneAxis Optional vector3 axis the bone is aligned with
  68174. */
  68175. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68176. var mesh = this.object;
  68177. if (mesh.rotationQuaternion) {
  68178. if (adjustRotation) {
  68179. var tempQuat = PhysicsImpostor._tmpQuat;
  68180. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68181. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68182. }
  68183. else {
  68184. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68185. }
  68186. }
  68187. var pos = PhysicsImpostor._tmpVecs[0];
  68188. var boneDir = PhysicsImpostor._tmpVecs[1];
  68189. if (!boneAxis) {
  68190. boneAxis = PhysicsImpostor._tmpVecs[2];
  68191. boneAxis.x = 0;
  68192. boneAxis.y = 1;
  68193. boneAxis.z = 0;
  68194. }
  68195. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68196. bone.getAbsolutePositionToRef(boneMesh, pos);
  68197. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68198. distToJoint = jointPivot.length();
  68199. }
  68200. if (distToJoint !== undefined && distToJoint !== null) {
  68201. pos.x += boneDir.x * distToJoint;
  68202. pos.y += boneDir.y * distToJoint;
  68203. pos.z += boneDir.z * distToJoint;
  68204. }
  68205. mesh.setAbsolutePosition(pos);
  68206. };
  68207. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68208. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68209. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68210. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68211. //Impostor types
  68212. PhysicsImpostor.NoImpostor = 0;
  68213. PhysicsImpostor.SphereImpostor = 1;
  68214. PhysicsImpostor.BoxImpostor = 2;
  68215. PhysicsImpostor.PlaneImpostor = 3;
  68216. PhysicsImpostor.MeshImpostor = 4;
  68217. PhysicsImpostor.CylinderImpostor = 7;
  68218. PhysicsImpostor.ParticleImpostor = 8;
  68219. PhysicsImpostor.HeightmapImpostor = 9;
  68220. return PhysicsImpostor;
  68221. }());
  68222. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68223. })(BABYLON || (BABYLON = {}));
  68224. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68225. var BABYLON;
  68226. (function (BABYLON) {
  68227. var PhysicsEngine = /** @class */ (function () {
  68228. function PhysicsEngine(gravity, _physicsPlugin) {
  68229. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68230. this._physicsPlugin = _physicsPlugin;
  68231. //new methods and parameters
  68232. this._impostors = [];
  68233. this._joints = [];
  68234. if (!this._physicsPlugin.isSupported()) {
  68235. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68236. + "Please make sure it is included.");
  68237. }
  68238. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68239. this.setGravity(gravity);
  68240. this.setTimeStep();
  68241. }
  68242. PhysicsEngine.prototype.setGravity = function (gravity) {
  68243. this.gravity = gravity;
  68244. this._physicsPlugin.setGravity(this.gravity);
  68245. };
  68246. /**
  68247. * Set the time step of the physics engine.
  68248. * default is 1/60.
  68249. * To slow it down, enter 1/600 for example.
  68250. * To speed it up, 1/30
  68251. * @param {number} newTimeStep the new timestep to apply to this world.
  68252. */
  68253. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68254. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68255. this._physicsPlugin.setTimeStep(newTimeStep);
  68256. };
  68257. /**
  68258. * Get the time step of the physics engine.
  68259. */
  68260. PhysicsEngine.prototype.getTimeStep = function () {
  68261. return this._physicsPlugin.getTimeStep();
  68262. };
  68263. PhysicsEngine.prototype.dispose = function () {
  68264. this._impostors.forEach(function (impostor) {
  68265. impostor.dispose();
  68266. });
  68267. this._physicsPlugin.dispose();
  68268. };
  68269. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68270. return this._physicsPlugin.name;
  68271. };
  68272. /**
  68273. * Adding a new impostor for the impostor tracking.
  68274. * This will be done by the impostor itself.
  68275. * @param {PhysicsImpostor} impostor the impostor to add
  68276. */
  68277. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68278. impostor.uniqueId = this._impostors.push(impostor);
  68279. //if no parent, generate the body
  68280. if (!impostor.parent) {
  68281. this._physicsPlugin.generatePhysicsBody(impostor);
  68282. }
  68283. };
  68284. /**
  68285. * Remove an impostor from the engine.
  68286. * This impostor and its mesh will not longer be updated by the physics engine.
  68287. * @param {PhysicsImpostor} impostor the impostor to remove
  68288. */
  68289. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68290. var index = this._impostors.indexOf(impostor);
  68291. if (index > -1) {
  68292. var removed = this._impostors.splice(index, 1);
  68293. //Is it needed?
  68294. if (removed.length) {
  68295. //this will also remove it from the world.
  68296. removed[0].physicsBody = null;
  68297. }
  68298. }
  68299. };
  68300. /**
  68301. * Add a joint to the physics engine
  68302. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68303. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68304. * @param {PhysicsJoint} the joint that will connect both impostors.
  68305. */
  68306. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68307. var impostorJoint = {
  68308. mainImpostor: mainImpostor,
  68309. connectedImpostor: connectedImpostor,
  68310. joint: joint
  68311. };
  68312. joint.physicsPlugin = this._physicsPlugin;
  68313. this._joints.push(impostorJoint);
  68314. this._physicsPlugin.generateJoint(impostorJoint);
  68315. };
  68316. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68317. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68318. return (impostorJoint.connectedImpostor === connectedImpostor
  68319. && impostorJoint.joint === joint
  68320. && impostorJoint.mainImpostor === mainImpostor);
  68321. });
  68322. if (matchingJoints.length) {
  68323. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68324. //TODO remove it from the list as well
  68325. }
  68326. };
  68327. /**
  68328. * Called by the scene. no need to call it.
  68329. */
  68330. PhysicsEngine.prototype._step = function (delta) {
  68331. var _this = this;
  68332. //check if any mesh has no body / requires an update
  68333. this._impostors.forEach(function (impostor) {
  68334. if (impostor.isBodyInitRequired()) {
  68335. _this._physicsPlugin.generatePhysicsBody(impostor);
  68336. }
  68337. });
  68338. if (delta > 0.1) {
  68339. delta = 0.1;
  68340. }
  68341. else if (delta <= 0) {
  68342. delta = 1.0 / 60.0;
  68343. }
  68344. this._physicsPlugin.executeStep(delta, this._impostors);
  68345. };
  68346. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68347. return this._physicsPlugin;
  68348. };
  68349. PhysicsEngine.prototype.getImpostors = function () {
  68350. return this._impostors;
  68351. };
  68352. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68353. for (var i = 0; i < this._impostors.length; ++i) {
  68354. if (this._impostors[i].object === object) {
  68355. return this._impostors[i];
  68356. }
  68357. }
  68358. return null;
  68359. };
  68360. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68361. for (var i = 0; i < this._impostors.length; ++i) {
  68362. if (this._impostors[i].physicsBody === body) {
  68363. return this._impostors[i];
  68364. }
  68365. }
  68366. return null;
  68367. };
  68368. // Statics
  68369. PhysicsEngine.Epsilon = 0.001;
  68370. return PhysicsEngine;
  68371. }());
  68372. BABYLON.PhysicsEngine = PhysicsEngine;
  68373. })(BABYLON || (BABYLON = {}));
  68374. //# sourceMappingURL=babylon.physicsEngine.js.map
  68375. var BABYLON;
  68376. (function (BABYLON) {
  68377. var PhysicsHelper = /** @class */ (function () {
  68378. function PhysicsHelper(scene) {
  68379. this._scene = scene;
  68380. this._physicsEngine = this._scene.getPhysicsEngine();
  68381. if (!this._physicsEngine) {
  68382. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68383. }
  68384. }
  68385. /**
  68386. * @param {Vector3} origin the origin of the explosion
  68387. * @param {number} radius the explosion radius
  68388. * @param {number} strength the explosion strength
  68389. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68390. */
  68391. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68392. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68393. if (!this._physicsEngine) {
  68394. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68395. return null;
  68396. }
  68397. var impostors = this._physicsEngine.getImpostors();
  68398. if (impostors.length === 0) {
  68399. return null;
  68400. }
  68401. var event = new PhysicsRadialExplosionEvent(this._scene);
  68402. impostors.forEach(function (impostor) {
  68403. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68404. if (!impostorForceAndContactPoint) {
  68405. return;
  68406. }
  68407. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68408. });
  68409. event.dispose(false);
  68410. return event;
  68411. };
  68412. /**
  68413. * @param {Vector3} origin the origin of the explosion
  68414. * @param {number} radius the explosion radius
  68415. * @param {number} strength the explosion strength
  68416. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68417. */
  68418. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68419. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68420. if (!this._physicsEngine) {
  68421. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68422. return null;
  68423. }
  68424. var impostors = this._physicsEngine.getImpostors();
  68425. if (impostors.length === 0) {
  68426. return null;
  68427. }
  68428. var event = new PhysicsRadialExplosionEvent(this._scene);
  68429. impostors.forEach(function (impostor) {
  68430. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68431. if (!impostorForceAndContactPoint) {
  68432. return;
  68433. }
  68434. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68435. });
  68436. event.dispose(false);
  68437. return event;
  68438. };
  68439. /**
  68440. * @param {Vector3} origin the origin of the explosion
  68441. * @param {number} radius the explosion radius
  68442. * @param {number} strength the explosion strength
  68443. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68444. */
  68445. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68446. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68447. if (!this._physicsEngine) {
  68448. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68449. return null;
  68450. }
  68451. var impostors = this._physicsEngine.getImpostors();
  68452. if (impostors.length === 0) {
  68453. return null;
  68454. }
  68455. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68456. event.dispose(false);
  68457. return event;
  68458. };
  68459. /**
  68460. * @param {Vector3} origin the origin of the updraft
  68461. * @param {number} radius the radius of the updraft
  68462. * @param {number} strength the strength of the updraft
  68463. * @param {number} height the height of the updraft
  68464. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68465. */
  68466. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68467. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68468. if (!this._physicsEngine) {
  68469. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68470. return null;
  68471. }
  68472. if (this._physicsEngine.getImpostors().length === 0) {
  68473. return null;
  68474. }
  68475. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68476. event.dispose(false);
  68477. return event;
  68478. };
  68479. /**
  68480. * @param {Vector3} origin the of the vortex
  68481. * @param {number} radius the radius of the vortex
  68482. * @param {number} strength the strength of the vortex
  68483. * @param {number} height the height of the vortex
  68484. */
  68485. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68486. if (!this._physicsEngine) {
  68487. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68488. return null;
  68489. }
  68490. if (this._physicsEngine.getImpostors().length === 0) {
  68491. return null;
  68492. }
  68493. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68494. event.dispose(false);
  68495. return event;
  68496. };
  68497. return PhysicsHelper;
  68498. }());
  68499. BABYLON.PhysicsHelper = PhysicsHelper;
  68500. /***** Radial explosion *****/
  68501. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68502. function PhysicsRadialExplosionEvent(scene) {
  68503. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68504. this._rays = [];
  68505. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68506. this._scene = scene;
  68507. }
  68508. /**
  68509. * Returns the data related to the radial explosion event (sphere & rays).
  68510. * @returns {PhysicsRadialExplosionEventData}
  68511. */
  68512. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68513. this._dataFetched = true;
  68514. return {
  68515. sphere: this._sphere,
  68516. rays: this._rays,
  68517. };
  68518. };
  68519. /**
  68520. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68521. * @param impostor
  68522. * @param {Vector3} origin the origin of the explosion
  68523. * @param {number} radius the explosion radius
  68524. * @param {number} strength the explosion strength
  68525. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68526. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68527. */
  68528. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68529. if (impostor.mass === 0) {
  68530. return null;
  68531. }
  68532. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68533. return null;
  68534. }
  68535. if (impostor.object.getClassName() !== 'Mesh') {
  68536. return null;
  68537. }
  68538. var impostorObject = impostor.object;
  68539. var impostorObjectCenter = impostor.getObjectCenter();
  68540. var direction = impostorObjectCenter.subtract(origin);
  68541. var ray = new BABYLON.Ray(origin, direction, radius);
  68542. this._rays.push(ray);
  68543. var hit = ray.intersectsMesh(impostorObject);
  68544. var contactPoint = hit.pickedPoint;
  68545. if (!contactPoint) {
  68546. return null;
  68547. }
  68548. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68549. if (distanceFromOrigin > radius) {
  68550. return null;
  68551. }
  68552. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68553. ? strength
  68554. : strength * (1 - (distanceFromOrigin / radius));
  68555. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68556. return { force: force, contactPoint: contactPoint };
  68557. };
  68558. /**
  68559. * Disposes the sphere.
  68560. * @param {bolean} force
  68561. */
  68562. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68563. var _this = this;
  68564. if (force === void 0) { force = true; }
  68565. if (force) {
  68566. this._sphere.dispose();
  68567. }
  68568. else {
  68569. setTimeout(function () {
  68570. if (!_this._dataFetched) {
  68571. _this._sphere.dispose();
  68572. }
  68573. }, 0);
  68574. }
  68575. };
  68576. /*** Helpers ***/
  68577. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68578. if (!this._sphere) {
  68579. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68580. this._sphere.isVisible = false;
  68581. }
  68582. };
  68583. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68584. var impostorObject = impostor.object;
  68585. this._prepareSphere();
  68586. this._sphere.position = origin;
  68587. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68588. this._sphere._updateBoundingInfo();
  68589. this._sphere.computeWorldMatrix(true);
  68590. return this._sphere.intersectsMesh(impostorObject, true);
  68591. };
  68592. return PhysicsRadialExplosionEvent;
  68593. }());
  68594. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68595. /***** Gravitational Field *****/
  68596. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68597. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68598. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68599. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68600. this._physicsHelper = physicsHelper;
  68601. this._scene = scene;
  68602. this._origin = origin;
  68603. this._radius = radius;
  68604. this._strength = strength;
  68605. this._falloff = falloff;
  68606. this._tickCallback = this._tick.bind(this);
  68607. }
  68608. /**
  68609. * Returns the data related to the gravitational field event (sphere).
  68610. * @returns {PhysicsGravitationalFieldEventData}
  68611. */
  68612. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68613. this._dataFetched = true;
  68614. return {
  68615. sphere: this._sphere,
  68616. };
  68617. };
  68618. /**
  68619. * Enables the gravitational field.
  68620. */
  68621. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68622. this._tickCallback.call(this);
  68623. this._scene.registerBeforeRender(this._tickCallback);
  68624. };
  68625. /**
  68626. * Disables the gravitational field.
  68627. */
  68628. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68629. this._scene.unregisterBeforeRender(this._tickCallback);
  68630. };
  68631. /**
  68632. * Disposes the sphere.
  68633. * @param {bolean} force
  68634. */
  68635. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68636. var _this = this;
  68637. if (force === void 0) { force = true; }
  68638. if (force) {
  68639. this._sphere.dispose();
  68640. }
  68641. else {
  68642. setTimeout(function () {
  68643. if (!_this._dataFetched) {
  68644. _this._sphere.dispose();
  68645. }
  68646. }, 0);
  68647. }
  68648. };
  68649. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68650. // Since the params won't change, we fetch the event only once
  68651. if (this._sphere) {
  68652. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68653. }
  68654. else {
  68655. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68656. if (radialExplosionEvent) {
  68657. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68658. }
  68659. }
  68660. };
  68661. return PhysicsGravitationalFieldEvent;
  68662. }());
  68663. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68664. /***** Updraft *****/
  68665. var PhysicsUpdraftEvent = /** @class */ (function () {
  68666. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68667. this._scene = _scene;
  68668. this._origin = _origin;
  68669. this._radius = _radius;
  68670. this._strength = _strength;
  68671. this._height = _height;
  68672. this._updraftMode = _updraftMode;
  68673. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68674. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68675. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68676. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68677. this._physicsEngine = this._scene.getPhysicsEngine();
  68678. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68679. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68680. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68681. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68682. }
  68683. this._tickCallback = this._tick.bind(this);
  68684. }
  68685. /**
  68686. * Returns the data related to the updraft event (cylinder).
  68687. * @returns {PhysicsUpdraftEventData}
  68688. */
  68689. PhysicsUpdraftEvent.prototype.getData = function () {
  68690. this._dataFetched = true;
  68691. return {
  68692. cylinder: this._cylinder,
  68693. };
  68694. };
  68695. /**
  68696. * Enables the updraft.
  68697. */
  68698. PhysicsUpdraftEvent.prototype.enable = function () {
  68699. this._tickCallback.call(this);
  68700. this._scene.registerBeforeRender(this._tickCallback);
  68701. };
  68702. /**
  68703. * Disables the cortex.
  68704. */
  68705. PhysicsUpdraftEvent.prototype.disable = function () {
  68706. this._scene.unregisterBeforeRender(this._tickCallback);
  68707. };
  68708. /**
  68709. * Disposes the sphere.
  68710. * @param {bolean} force
  68711. */
  68712. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  68713. var _this = this;
  68714. if (force === void 0) { force = true; }
  68715. if (force) {
  68716. this._cylinder.dispose();
  68717. }
  68718. else {
  68719. setTimeout(function () {
  68720. if (!_this._dataFetched) {
  68721. _this._cylinder.dispose();
  68722. }
  68723. }, 0);
  68724. }
  68725. };
  68726. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68727. if (impostor.mass === 0) {
  68728. return null;
  68729. }
  68730. if (!this._intersectsWithCylinder(impostor)) {
  68731. return null;
  68732. }
  68733. var impostorObjectCenter = impostor.getObjectCenter();
  68734. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68735. var direction = this._originDirection;
  68736. }
  68737. else {
  68738. var direction = impostorObjectCenter.subtract(this._originTop);
  68739. }
  68740. var multiplier = this._strength * -1;
  68741. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68742. return { force: force, contactPoint: impostorObjectCenter };
  68743. };
  68744. PhysicsUpdraftEvent.prototype._tick = function () {
  68745. var _this = this;
  68746. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68747. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68748. if (!impostorForceAndContactPoint) {
  68749. return;
  68750. }
  68751. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68752. });
  68753. };
  68754. /*** Helpers ***/
  68755. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  68756. if (!this._cylinder) {
  68757. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  68758. height: this._height,
  68759. diameter: this._radius * 2,
  68760. }, this._scene);
  68761. this._cylinder.isVisible = false;
  68762. }
  68763. };
  68764. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  68765. var impostorObject = impostor.object;
  68766. this._prepareCylinder();
  68767. this._cylinder.position = this._cylinderPosition;
  68768. return this._cylinder.intersectsMesh(impostorObject, true);
  68769. };
  68770. return PhysicsUpdraftEvent;
  68771. }());
  68772. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  68773. /***** Vortex *****/
  68774. var PhysicsVortexEvent = /** @class */ (function () {
  68775. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  68776. this._scene = _scene;
  68777. this._origin = _origin;
  68778. this._radius = _radius;
  68779. this._strength = _strength;
  68780. this._height = _height;
  68781. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68782. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  68783. this._updraftMultiplier = 0.02;
  68784. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68785. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68786. this._physicsEngine = this._scene.getPhysicsEngine();
  68787. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68788. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68789. this._tickCallback = this._tick.bind(this);
  68790. }
  68791. /**
  68792. * Returns the data related to the vortex event (cylinder).
  68793. * @returns {PhysicsVortexEventData}
  68794. */
  68795. PhysicsVortexEvent.prototype.getData = function () {
  68796. this._dataFetched = true;
  68797. return {
  68798. cylinder: this._cylinder,
  68799. };
  68800. };
  68801. /**
  68802. * Enables the vortex.
  68803. */
  68804. PhysicsVortexEvent.prototype.enable = function () {
  68805. this._tickCallback.call(this);
  68806. this._scene.registerBeforeRender(this._tickCallback);
  68807. };
  68808. /**
  68809. * Disables the cortex.
  68810. */
  68811. PhysicsVortexEvent.prototype.disable = function () {
  68812. this._scene.unregisterBeforeRender(this._tickCallback);
  68813. };
  68814. /**
  68815. * Disposes the sphere.
  68816. * @param {bolean} force
  68817. */
  68818. PhysicsVortexEvent.prototype.dispose = function (force) {
  68819. var _this = this;
  68820. if (force === void 0) { force = true; }
  68821. if (force) {
  68822. this._cylinder.dispose();
  68823. }
  68824. else {
  68825. setTimeout(function () {
  68826. if (!_this._dataFetched) {
  68827. _this._cylinder.dispose();
  68828. }
  68829. }, 0);
  68830. }
  68831. };
  68832. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68833. if (impostor.mass === 0) {
  68834. return null;
  68835. }
  68836. if (!this._intersectsWithCylinder(impostor)) {
  68837. return null;
  68838. }
  68839. if (impostor.object.getClassName() !== 'Mesh') {
  68840. return null;
  68841. }
  68842. var impostorObject = impostor.object;
  68843. var impostorObjectCenter = impostor.getObjectCenter();
  68844. 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)
  68845. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  68846. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  68847. var hit = ray.intersectsMesh(impostorObject);
  68848. var contactPoint = hit.pickedPoint;
  68849. if (!contactPoint) {
  68850. return null;
  68851. }
  68852. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  68853. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  68854. var directionToOrigin = contactPoint.normalize();
  68855. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68856. directionToOrigin = directionToOrigin.negate();
  68857. }
  68858. // TODO: find a more physically based solution
  68859. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68860. var forceX = directionToOrigin.x * this._strength / 8;
  68861. var forceY = directionToOrigin.y * this._updraftMultiplier;
  68862. var forceZ = directionToOrigin.z * this._strength / 8;
  68863. }
  68864. else {
  68865. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  68866. var forceY = this._originTop.y * this._updraftMultiplier;
  68867. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  68868. }
  68869. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  68870. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  68871. return { force: force, contactPoint: impostorObjectCenter };
  68872. };
  68873. PhysicsVortexEvent.prototype._tick = function () {
  68874. var _this = this;
  68875. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68876. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68877. if (!impostorForceAndContactPoint) {
  68878. return;
  68879. }
  68880. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68881. });
  68882. };
  68883. /*** Helpers ***/
  68884. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  68885. if (!this._cylinder) {
  68886. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  68887. height: this._height,
  68888. diameter: this._radius * 2,
  68889. }, this._scene);
  68890. this._cylinder.isVisible = false;
  68891. }
  68892. };
  68893. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  68894. var impostorObject = impostor.object;
  68895. this._prepareCylinder();
  68896. this._cylinder.position = this._cylinderPosition;
  68897. return this._cylinder.intersectsMesh(impostorObject, true);
  68898. };
  68899. return PhysicsVortexEvent;
  68900. }());
  68901. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  68902. /***** Enums *****/
  68903. /**
  68904. * The strenght of the force in correspondence to the distance of the affected object
  68905. */
  68906. var PhysicsRadialImpulseFalloff;
  68907. (function (PhysicsRadialImpulseFalloff) {
  68908. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  68909. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  68910. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  68911. /**
  68912. * The strenght of the force in correspondence to the distance of the affected object
  68913. */
  68914. var PhysicsUpdraftMode;
  68915. (function (PhysicsUpdraftMode) {
  68916. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  68917. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  68918. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  68919. })(BABYLON || (BABYLON = {}));
  68920. //# sourceMappingURL=babylon.physicsHelper.js.map
  68921. var BABYLON;
  68922. (function (BABYLON) {
  68923. var CannonJSPlugin = /** @class */ (function () {
  68924. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  68925. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  68926. if (iterations === void 0) { iterations = 10; }
  68927. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  68928. this.name = "CannonJSPlugin";
  68929. this._physicsMaterials = new Array();
  68930. this._fixedTimeStep = 1 / 60;
  68931. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  68932. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  68933. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  68934. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  68935. this._tmpPosition = BABYLON.Vector3.Zero();
  68936. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  68937. this._tmpUnityRotation = new BABYLON.Quaternion();
  68938. if (!this.isSupported()) {
  68939. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  68940. return;
  68941. }
  68942. this._extendNamespace();
  68943. this.world = new this.BJSCANNON.World();
  68944. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  68945. this.world.solver.iterations = iterations;
  68946. }
  68947. CannonJSPlugin.prototype.setGravity = function (gravity) {
  68948. this.world.gravity.copy(gravity);
  68949. };
  68950. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  68951. this._fixedTimeStep = timeStep;
  68952. };
  68953. CannonJSPlugin.prototype.getTimeStep = function () {
  68954. return this._fixedTimeStep;
  68955. };
  68956. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  68957. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  68958. };
  68959. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68960. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68961. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68962. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  68963. };
  68964. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68965. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68966. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68967. impostor.physicsBody.applyForce(impulse, worldPoint);
  68968. };
  68969. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68970. //parent-child relationship. Does this impostor has a parent impostor?
  68971. if (impostor.parent) {
  68972. if (impostor.physicsBody) {
  68973. this.removePhysicsBody(impostor);
  68974. //TODO is that needed?
  68975. impostor.forceUpdate();
  68976. }
  68977. return;
  68978. }
  68979. //should a new body be created for this impostor?
  68980. if (impostor.isBodyInitRequired()) {
  68981. var shape = this._createShape(impostor);
  68982. //unregister events, if body is being changed
  68983. var oldBody = impostor.physicsBody;
  68984. if (oldBody) {
  68985. this.removePhysicsBody(impostor);
  68986. }
  68987. //create the body and material
  68988. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  68989. var bodyCreationObject = {
  68990. mass: impostor.getParam("mass"),
  68991. material: material
  68992. };
  68993. // A simple extend, in case native options were used.
  68994. var nativeOptions = impostor.getParam("nativeOptions");
  68995. for (var key in nativeOptions) {
  68996. if (nativeOptions.hasOwnProperty(key)) {
  68997. bodyCreationObject[key] = nativeOptions[key];
  68998. }
  68999. }
  69000. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69001. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69002. this.world.addEventListener("preStep", impostor.beforeStep);
  69003. this.world.addEventListener("postStep", impostor.afterStep);
  69004. impostor.physicsBody.addShape(shape);
  69005. this.world.add(impostor.physicsBody);
  69006. //try to keep the body moving in the right direction by taking old properties.
  69007. //Should be tested!
  69008. if (oldBody) {
  69009. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69010. impostor.physicsBody[param].copy(oldBody[param]);
  69011. });
  69012. }
  69013. this._processChildMeshes(impostor);
  69014. }
  69015. //now update the body's transformation
  69016. this._updatePhysicsBodyTransformation(impostor);
  69017. };
  69018. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69019. var _this = this;
  69020. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69021. var currentRotation = mainImpostor.object.rotationQuaternion;
  69022. if (meshChildren.length) {
  69023. var processMesh = function (localPosition, mesh) {
  69024. if (!currentRotation || !mesh.rotationQuaternion) {
  69025. return;
  69026. }
  69027. var childImpostor = mesh.getPhysicsImpostor();
  69028. if (childImpostor) {
  69029. var parent = childImpostor.parent;
  69030. if (parent !== mainImpostor) {
  69031. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69032. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69033. if (childImpostor.physicsBody) {
  69034. _this.removePhysicsBody(childImpostor);
  69035. childImpostor.physicsBody = null;
  69036. }
  69037. childImpostor.parent = mainImpostor;
  69038. childImpostor.resetUpdateFlags();
  69039. 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));
  69040. //Add the mass of the children.
  69041. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69042. }
  69043. }
  69044. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69045. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69046. };
  69047. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69048. }
  69049. };
  69050. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69051. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69052. this.world.removeEventListener("preStep", impostor.beforeStep);
  69053. this.world.removeEventListener("postStep", impostor.afterStep);
  69054. this.world.remove(impostor.physicsBody);
  69055. };
  69056. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69057. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69058. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69059. if (!mainBody || !connectedBody) {
  69060. return;
  69061. }
  69062. var constraint;
  69063. var jointData = impostorJoint.joint.jointData;
  69064. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69065. var constraintData = {
  69066. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69067. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69068. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69069. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69070. maxForce: jointData.nativeParams.maxForce,
  69071. collideConnected: !!jointData.collision
  69072. };
  69073. switch (impostorJoint.joint.type) {
  69074. case BABYLON.PhysicsJoint.HingeJoint:
  69075. case BABYLON.PhysicsJoint.Hinge2Joint:
  69076. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69077. break;
  69078. case BABYLON.PhysicsJoint.DistanceJoint:
  69079. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69080. break;
  69081. case BABYLON.PhysicsJoint.SpringJoint:
  69082. var springData = jointData;
  69083. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69084. restLength: springData.length,
  69085. stiffness: springData.stiffness,
  69086. damping: springData.damping,
  69087. localAnchorA: constraintData.pivotA,
  69088. localAnchorB: constraintData.pivotB
  69089. });
  69090. break;
  69091. case BABYLON.PhysicsJoint.LockJoint:
  69092. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69093. break;
  69094. case BABYLON.PhysicsJoint.PointToPointJoint:
  69095. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69096. default:
  69097. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69098. break;
  69099. }
  69100. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69101. constraint.collideConnected = !!jointData.collision;
  69102. impostorJoint.joint.physicsJoint = constraint;
  69103. //don't add spring as constraint, as it is not one.
  69104. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69105. this.world.addConstraint(constraint);
  69106. }
  69107. else {
  69108. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69109. constraint.applyForce();
  69110. });
  69111. }
  69112. };
  69113. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69114. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69115. };
  69116. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69117. var index;
  69118. var mat;
  69119. for (index = 0; index < this._physicsMaterials.length; index++) {
  69120. mat = this._physicsMaterials[index];
  69121. if (mat.friction === friction && mat.restitution === restitution) {
  69122. return mat;
  69123. }
  69124. }
  69125. var currentMat = new this.BJSCANNON.Material(name);
  69126. currentMat.friction = friction;
  69127. currentMat.restitution = restitution;
  69128. this._physicsMaterials.push(currentMat);
  69129. return currentMat;
  69130. };
  69131. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69132. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69133. };
  69134. CannonJSPlugin.prototype._createShape = function (impostor) {
  69135. var object = impostor.object;
  69136. var returnValue;
  69137. var extendSize = impostor.getObjectExtendSize();
  69138. switch (impostor.type) {
  69139. case BABYLON.PhysicsImpostor.SphereImpostor:
  69140. var radiusX = extendSize.x;
  69141. var radiusY = extendSize.y;
  69142. var radiusZ = extendSize.z;
  69143. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69144. break;
  69145. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69146. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69147. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69148. break;
  69149. case BABYLON.PhysicsImpostor.BoxImpostor:
  69150. var box = extendSize.scale(0.5);
  69151. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69152. break;
  69153. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69154. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69155. returnValue = new this.BJSCANNON.Plane();
  69156. break;
  69157. case BABYLON.PhysicsImpostor.MeshImpostor:
  69158. // should transform the vertex data to world coordinates!!
  69159. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69160. var rawFaces = object.getIndices ? object.getIndices() : [];
  69161. if (!rawVerts)
  69162. return;
  69163. // get only scale! so the object could transform correctly.
  69164. var oldPosition = object.position.clone();
  69165. var oldRotation = object.rotation && object.rotation.clone();
  69166. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69167. object.position.copyFromFloats(0, 0, 0);
  69168. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69169. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69170. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69171. var transform = object.computeWorldMatrix(true);
  69172. // convert rawVerts to object space
  69173. var temp = new Array();
  69174. var index;
  69175. for (index = 0; index < rawVerts.length; index += 3) {
  69176. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69177. }
  69178. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69179. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69180. //now set back the transformation!
  69181. object.position.copyFrom(oldPosition);
  69182. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69183. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69184. break;
  69185. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69186. var oldPosition2 = object.position.clone();
  69187. var oldRotation2 = object.rotation && object.rotation.clone();
  69188. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69189. object.position.copyFromFloats(0, 0, 0);
  69190. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69191. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69192. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69193. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69194. returnValue = this._createHeightmap(object);
  69195. object.position.copyFrom(oldPosition2);
  69196. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69197. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69198. object.computeWorldMatrix(true);
  69199. break;
  69200. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69201. returnValue = new this.BJSCANNON.Particle();
  69202. break;
  69203. }
  69204. return returnValue;
  69205. };
  69206. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69207. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69208. var transform = object.computeWorldMatrix(true);
  69209. // convert rawVerts to object space
  69210. var temp = new Array();
  69211. var index;
  69212. for (index = 0; index < pos.length; index += 3) {
  69213. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69214. }
  69215. pos = temp;
  69216. var matrix = new Array();
  69217. //For now pointDepth will not be used and will be automatically calculated.
  69218. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69219. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69220. var boundingInfo = object.getBoundingInfo();
  69221. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69222. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69223. var elementSize = dim * 2 / arraySize;
  69224. for (var i = 0; i < pos.length; i = i + 3) {
  69225. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69226. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69227. var y = -pos[i + 2] + minY;
  69228. if (!matrix[x]) {
  69229. matrix[x] = [];
  69230. }
  69231. if (!matrix[x][z]) {
  69232. matrix[x][z] = y;
  69233. }
  69234. matrix[x][z] = Math.max(y, matrix[x][z]);
  69235. }
  69236. for (var x = 0; x <= arraySize; ++x) {
  69237. if (!matrix[x]) {
  69238. var loc = 1;
  69239. while (!matrix[(x + loc) % arraySize]) {
  69240. loc++;
  69241. }
  69242. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69243. //console.log("missing x", x);
  69244. }
  69245. for (var z = 0; z <= arraySize; ++z) {
  69246. if (!matrix[x][z]) {
  69247. var loc = 1;
  69248. var newValue;
  69249. while (newValue === undefined) {
  69250. newValue = matrix[x][(z + loc++) % arraySize];
  69251. }
  69252. matrix[x][z] = newValue;
  69253. }
  69254. }
  69255. }
  69256. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69257. elementSize: elementSize
  69258. });
  69259. //For future reference, needed for body transformation
  69260. shape.minY = minY;
  69261. return shape;
  69262. };
  69263. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69264. var object = impostor.object;
  69265. //make sure it is updated...
  69266. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69267. // The delta between the mesh position and the mesh bounding box center
  69268. var bInfo = object.getBoundingInfo();
  69269. if (!bInfo)
  69270. return;
  69271. var center = impostor.getObjectCenter();
  69272. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69273. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69274. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69275. this._tmpPosition.copyFrom(center);
  69276. var quaternion = object.rotationQuaternion;
  69277. if (!quaternion) {
  69278. return;
  69279. }
  69280. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69281. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69282. //-90 DEG in X, precalculated
  69283. quaternion = quaternion.multiply(this._minus90X);
  69284. //Invert! (Precalculated, 90 deg in X)
  69285. //No need to clone. this will never change.
  69286. impostor.setDeltaRotation(this._plus90X);
  69287. }
  69288. //If it is a heightfield, if should be centered.
  69289. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69290. var mesh = object;
  69291. var boundingInfo = mesh.getBoundingInfo();
  69292. //calculate the correct body position:
  69293. var rotationQuaternion = mesh.rotationQuaternion;
  69294. mesh.rotationQuaternion = this._tmpUnityRotation;
  69295. mesh.computeWorldMatrix(true);
  69296. //get original center with no rotation
  69297. var c = center.clone();
  69298. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69299. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69300. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69301. mesh.setPivotMatrix(p);
  69302. mesh.computeWorldMatrix(true);
  69303. //calculate the translation
  69304. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69305. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69306. //add it inverted to the delta
  69307. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69308. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69309. //rotation is back
  69310. mesh.rotationQuaternion = rotationQuaternion;
  69311. mesh.setPivotMatrix(oldPivot);
  69312. mesh.computeWorldMatrix(true);
  69313. }
  69314. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69315. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69316. //this._tmpPosition.copyFrom(object.position);
  69317. }
  69318. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69319. //Now update the impostor object
  69320. impostor.physicsBody.position.copy(this._tmpPosition);
  69321. impostor.physicsBody.quaternion.copy(quaternion);
  69322. };
  69323. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69324. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69325. if (impostor.object.rotationQuaternion) {
  69326. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69327. }
  69328. };
  69329. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69330. impostor.physicsBody.position.copy(newPosition);
  69331. impostor.physicsBody.quaternion.copy(newRotation);
  69332. };
  69333. CannonJSPlugin.prototype.isSupported = function () {
  69334. return this.BJSCANNON !== undefined;
  69335. };
  69336. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69337. impostor.physicsBody.velocity.copy(velocity);
  69338. };
  69339. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69340. impostor.physicsBody.angularVelocity.copy(velocity);
  69341. };
  69342. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69343. var v = impostor.physicsBody.velocity;
  69344. if (!v) {
  69345. return null;
  69346. }
  69347. return new BABYLON.Vector3(v.x, v.y, v.z);
  69348. };
  69349. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69350. var v = impostor.physicsBody.angularVelocity;
  69351. if (!v) {
  69352. return null;
  69353. }
  69354. return new BABYLON.Vector3(v.x, v.y, v.z);
  69355. };
  69356. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69357. impostor.physicsBody.mass = mass;
  69358. impostor.physicsBody.updateMassProperties();
  69359. };
  69360. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69361. return impostor.physicsBody.mass;
  69362. };
  69363. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69364. return impostor.physicsBody.material.friction;
  69365. };
  69366. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69367. impostor.physicsBody.material.friction = friction;
  69368. };
  69369. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69370. return impostor.physicsBody.material.restitution;
  69371. };
  69372. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69373. impostor.physicsBody.material.restitution = restitution;
  69374. };
  69375. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69376. impostor.physicsBody.sleep();
  69377. };
  69378. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69379. impostor.physicsBody.wakeUp();
  69380. };
  69381. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69382. joint.physicsJoint.distance = maxDistance;
  69383. };
  69384. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69385. // if (!motorIndex) {
  69386. // joint.physicsJoint.enableMotor();
  69387. // }
  69388. // }
  69389. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69390. // if (!motorIndex) {
  69391. // joint.physicsJoint.disableMotor();
  69392. // }
  69393. // }
  69394. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69395. if (!motorIndex) {
  69396. joint.physicsJoint.enableMotor();
  69397. joint.physicsJoint.setMotorSpeed(speed);
  69398. if (maxForce) {
  69399. this.setLimit(joint, maxForce);
  69400. }
  69401. }
  69402. };
  69403. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69404. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69405. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69406. };
  69407. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69408. var body = impostor.physicsBody;
  69409. mesh.position.x = body.position.x;
  69410. mesh.position.y = body.position.y;
  69411. mesh.position.z = body.position.z;
  69412. if (mesh.rotationQuaternion) {
  69413. mesh.rotationQuaternion.x = body.quaternion.x;
  69414. mesh.rotationQuaternion.y = body.quaternion.y;
  69415. mesh.rotationQuaternion.z = body.quaternion.z;
  69416. mesh.rotationQuaternion.w = body.quaternion.w;
  69417. }
  69418. };
  69419. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69420. var shape = impostor.physicsBody.shapes[0];
  69421. return shape.boundingSphereRadius;
  69422. };
  69423. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69424. var shape = impostor.physicsBody.shapes[0];
  69425. result.x = shape.halfExtents.x * 2;
  69426. result.y = shape.halfExtents.y * 2;
  69427. result.z = shape.halfExtents.z * 2;
  69428. };
  69429. CannonJSPlugin.prototype.dispose = function () {
  69430. };
  69431. CannonJSPlugin.prototype._extendNamespace = function () {
  69432. //this will force cannon to execute at least one step when using interpolation
  69433. var step_tmp1 = new this.BJSCANNON.Vec3();
  69434. var Engine = this.BJSCANNON;
  69435. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69436. maxSubSteps = maxSubSteps || 10;
  69437. timeSinceLastCalled = timeSinceLastCalled || 0;
  69438. if (timeSinceLastCalled === 0) {
  69439. this.internalStep(dt);
  69440. this.time += dt;
  69441. }
  69442. else {
  69443. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69444. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69445. var t0 = performance.now();
  69446. for (var i = 0; i !== internalSteps; i++) {
  69447. this.internalStep(dt);
  69448. if (performance.now() - t0 > dt * 1000) {
  69449. break;
  69450. }
  69451. }
  69452. this.time += timeSinceLastCalled;
  69453. var h = this.time % dt;
  69454. var h_div_dt = h / dt;
  69455. var interpvelo = step_tmp1;
  69456. var bodies = this.bodies;
  69457. for (var j = 0; j !== bodies.length; j++) {
  69458. var b = bodies[j];
  69459. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69460. b.position.vsub(b.previousPosition, interpvelo);
  69461. interpvelo.scale(h_div_dt, interpvelo);
  69462. b.position.vadd(interpvelo, b.interpolatedPosition);
  69463. }
  69464. else {
  69465. b.interpolatedPosition.copy(b.position);
  69466. b.interpolatedQuaternion.copy(b.quaternion);
  69467. }
  69468. }
  69469. }
  69470. };
  69471. };
  69472. return CannonJSPlugin;
  69473. }());
  69474. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69475. })(BABYLON || (BABYLON = {}));
  69476. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69477. var BABYLON;
  69478. (function (BABYLON) {
  69479. var OimoJSPlugin = /** @class */ (function () {
  69480. function OimoJSPlugin(iterations) {
  69481. this.name = "OimoJSPlugin";
  69482. this._tmpImpostorsArray = [];
  69483. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69484. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69485. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69486. this.world.worldscale(1);
  69487. this.world.clear();
  69488. //making sure no stats are calculated
  69489. this.world.isNoStat = true;
  69490. }
  69491. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69492. this.world.gravity.copy(gravity);
  69493. };
  69494. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69495. this.world.timeStep = timeStep;
  69496. };
  69497. OimoJSPlugin.prototype.getTimeStep = function () {
  69498. return this.world.timeStep;
  69499. };
  69500. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69501. var _this = this;
  69502. impostors.forEach(function (impostor) {
  69503. impostor.beforeStep();
  69504. });
  69505. this.world.step();
  69506. impostors.forEach(function (impostor) {
  69507. impostor.afterStep();
  69508. //update the ordered impostors array
  69509. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69510. });
  69511. //check for collisions
  69512. var contact = this.world.contacts;
  69513. while (contact !== null) {
  69514. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69515. contact = contact.next;
  69516. continue;
  69517. }
  69518. //is this body colliding with any other? get the impostor
  69519. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69520. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69521. if (!mainImpostor || !collidingImpostor) {
  69522. contact = contact.next;
  69523. continue;
  69524. }
  69525. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69526. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69527. contact = contact.next;
  69528. }
  69529. };
  69530. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69531. var mass = impostor.physicsBody.massInfo.mass;
  69532. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69533. };
  69534. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69535. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69536. this.applyImpulse(impostor, force, contactPoint);
  69537. };
  69538. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69539. var _this = this;
  69540. //parent-child relationship. Does this impostor has a parent impostor?
  69541. if (impostor.parent) {
  69542. if (impostor.physicsBody) {
  69543. this.removePhysicsBody(impostor);
  69544. //TODO is that needed?
  69545. impostor.forceUpdate();
  69546. }
  69547. return;
  69548. }
  69549. if (impostor.isBodyInitRequired()) {
  69550. var bodyConfig = {
  69551. name: impostor.uniqueId,
  69552. //Oimo must have mass, also for static objects.
  69553. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69554. size: [],
  69555. type: [],
  69556. pos: [],
  69557. rot: [],
  69558. move: impostor.getParam("mass") !== 0,
  69559. //Supporting older versions of Oimo
  69560. world: this.world
  69561. };
  69562. var impostors = [impostor];
  69563. var addToArray = function (parent) {
  69564. if (!parent.getChildMeshes)
  69565. return;
  69566. parent.getChildMeshes().forEach(function (m) {
  69567. if (m.physicsImpostor) {
  69568. impostors.push(m.physicsImpostor);
  69569. //m.physicsImpostor._init();
  69570. }
  69571. });
  69572. };
  69573. addToArray(impostor.object);
  69574. var checkWithEpsilon_1 = function (value) {
  69575. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69576. };
  69577. impostors.forEach(function (i) {
  69578. if (!impostor.object.rotationQuaternion) {
  69579. return;
  69580. }
  69581. //get the correct bounding box
  69582. var oldQuaternion = i.object.rotationQuaternion;
  69583. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69584. x: impostor.object.rotationQuaternion.x,
  69585. y: impostor.object.rotationQuaternion.y,
  69586. z: impostor.object.rotationQuaternion.z,
  69587. s: impostor.object.rotationQuaternion.w
  69588. });
  69589. var extendSize = i.getObjectExtendSize();
  69590. if (i === impostor) {
  69591. var center = impostor.getObjectCenter();
  69592. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  69593. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  69594. //Can also use Array.prototype.push.apply
  69595. bodyConfig.pos.push(center.x);
  69596. bodyConfig.pos.push(center.y);
  69597. bodyConfig.pos.push(center.z);
  69598. //tmp solution
  69599. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69600. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69601. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69602. }
  69603. else {
  69604. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69605. bodyConfig.pos.push(localPosition.x);
  69606. bodyConfig.pos.push(localPosition.y);
  69607. bodyConfig.pos.push(localPosition.z);
  69608. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69609. bodyConfig.rot.push(0);
  69610. bodyConfig.rot.push(0);
  69611. bodyConfig.rot.push(0);
  69612. }
  69613. // register mesh
  69614. switch (i.type) {
  69615. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69616. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69617. case BABYLON.PhysicsImpostor.SphereImpostor:
  69618. var radiusX = extendSize.x;
  69619. var radiusY = extendSize.y;
  69620. var radiusZ = extendSize.z;
  69621. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69622. bodyConfig.type.push('sphere');
  69623. //due to the way oimo works with compounds, add 3 times
  69624. bodyConfig.size.push(size);
  69625. bodyConfig.size.push(size);
  69626. bodyConfig.size.push(size);
  69627. break;
  69628. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69629. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69630. var sizeY = checkWithEpsilon_1(extendSize.y);
  69631. bodyConfig.type.push('cylinder');
  69632. bodyConfig.size.push(sizeX);
  69633. bodyConfig.size.push(sizeY);
  69634. //due to the way oimo works with compounds, add one more value.
  69635. bodyConfig.size.push(sizeY);
  69636. break;
  69637. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69638. case BABYLON.PhysicsImpostor.BoxImpostor:
  69639. default:
  69640. var sizeX = checkWithEpsilon_1(extendSize.x);
  69641. var sizeY = checkWithEpsilon_1(extendSize.y);
  69642. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69643. bodyConfig.type.push('box');
  69644. bodyConfig.size.push(sizeX);
  69645. bodyConfig.size.push(sizeY);
  69646. bodyConfig.size.push(sizeZ);
  69647. break;
  69648. }
  69649. //actually not needed, but hey...
  69650. i.object.rotationQuaternion = oldQuaternion;
  69651. });
  69652. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69653. }
  69654. else {
  69655. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69656. }
  69657. impostor.setDeltaPosition(this._tmpPositionVector);
  69658. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69659. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69660. };
  69661. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69662. //impostor.physicsBody.dispose();
  69663. //Same as : (older oimo versions)
  69664. this.world.removeRigidBody(impostor.physicsBody);
  69665. };
  69666. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69667. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69668. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69669. if (!mainBody || !connectedBody) {
  69670. return;
  69671. }
  69672. var jointData = impostorJoint.joint.jointData;
  69673. var options = jointData.nativeParams || {};
  69674. var type;
  69675. var nativeJointData = {
  69676. body1: mainBody,
  69677. body2: connectedBody,
  69678. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69679. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69680. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69681. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69682. min: options.min,
  69683. max: options.max,
  69684. collision: options.collision || jointData.collision,
  69685. spring: options.spring,
  69686. //supporting older version of Oimo
  69687. world: this.world
  69688. };
  69689. switch (impostorJoint.joint.type) {
  69690. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69691. type = "jointBall";
  69692. break;
  69693. case BABYLON.PhysicsJoint.SpringJoint:
  69694. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69695. var springData = jointData;
  69696. nativeJointData.min = springData.length || nativeJointData.min;
  69697. //Max should also be set, just make sure it is at least min
  69698. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  69699. case BABYLON.PhysicsJoint.DistanceJoint:
  69700. type = "jointDistance";
  69701. nativeJointData.max = jointData.maxDistance;
  69702. break;
  69703. case BABYLON.PhysicsJoint.PrismaticJoint:
  69704. type = "jointPrisme";
  69705. break;
  69706. case BABYLON.PhysicsJoint.SliderJoint:
  69707. type = "jointSlide";
  69708. break;
  69709. case BABYLON.PhysicsJoint.WheelJoint:
  69710. type = "jointWheel";
  69711. break;
  69712. case BABYLON.PhysicsJoint.HingeJoint:
  69713. default:
  69714. type = "jointHinge";
  69715. break;
  69716. }
  69717. nativeJointData.type = type;
  69718. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  69719. };
  69720. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69721. //Bug in Oimo prevents us from disposing a joint in the playground
  69722. //joint.joint.physicsJoint.dispose();
  69723. //So we will bruteforce it!
  69724. try {
  69725. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  69726. }
  69727. catch (e) {
  69728. BABYLON.Tools.Warn(e);
  69729. }
  69730. };
  69731. OimoJSPlugin.prototype.isSupported = function () {
  69732. return this.BJSOIMO !== undefined;
  69733. };
  69734. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69735. if (!impostor.physicsBody.sleeping) {
  69736. //TODO check that
  69737. if (impostor.physicsBody.shapes.next) {
  69738. var parentShape = this._getLastShape(impostor.physicsBody);
  69739. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  69740. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  69741. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  69742. }
  69743. else {
  69744. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  69745. }
  69746. if (impostor.object.rotationQuaternion) {
  69747. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  69748. impostor.object.rotationQuaternion.normalize();
  69749. }
  69750. }
  69751. };
  69752. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69753. var body = impostor.physicsBody;
  69754. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  69755. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  69756. body.syncShapes();
  69757. body.awake();
  69758. };
  69759. OimoJSPlugin.prototype._getLastShape = function (body) {
  69760. var lastShape = body.shapes;
  69761. while (lastShape.next) {
  69762. lastShape = lastShape.next;
  69763. }
  69764. return lastShape;
  69765. };
  69766. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69767. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  69768. };
  69769. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69770. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  69771. };
  69772. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69773. var v = impostor.physicsBody.linearVelocity;
  69774. if (!v) {
  69775. return null;
  69776. }
  69777. return new BABYLON.Vector3(v.x, v.y, v.z);
  69778. };
  69779. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69780. var v = impostor.physicsBody.angularVelocity;
  69781. if (!v) {
  69782. return null;
  69783. }
  69784. return new BABYLON.Vector3(v.x, v.y, v.z);
  69785. };
  69786. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69787. var staticBody = mass === 0;
  69788. //this will actually set the body's density and not its mass.
  69789. //But this is how oimo treats the mass variable.
  69790. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  69791. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  69792. };
  69793. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  69794. return impostor.physicsBody.shapes.density;
  69795. };
  69796. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  69797. return impostor.physicsBody.shapes.friction;
  69798. };
  69799. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69800. impostor.physicsBody.shapes.friction = friction;
  69801. };
  69802. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69803. return impostor.physicsBody.shapes.restitution;
  69804. };
  69805. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69806. impostor.physicsBody.shapes.restitution = restitution;
  69807. };
  69808. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  69809. impostor.physicsBody.sleep();
  69810. };
  69811. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  69812. impostor.physicsBody.awake();
  69813. };
  69814. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69815. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  69816. if (minDistance !== void 0) {
  69817. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  69818. }
  69819. };
  69820. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69821. //TODO separate rotational and transational motors.
  69822. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  69823. if (motor) {
  69824. motor.setMotor(speed, maxForce);
  69825. }
  69826. };
  69827. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  69828. //TODO separate rotational and transational motors.
  69829. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  69830. if (motor) {
  69831. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  69832. }
  69833. };
  69834. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69835. var body = impostor.physicsBody;
  69836. mesh.position.x = body.position.x;
  69837. mesh.position.y = body.position.y;
  69838. mesh.position.z = body.position.z;
  69839. if (mesh.rotationQuaternion) {
  69840. mesh.rotationQuaternion.x = body.orientation.x;
  69841. mesh.rotationQuaternion.y = body.orientation.y;
  69842. mesh.rotationQuaternion.z = body.orientation.z;
  69843. mesh.rotationQuaternion.w = body.orientation.s;
  69844. }
  69845. };
  69846. OimoJSPlugin.prototype.getRadius = function (impostor) {
  69847. return impostor.physicsBody.shapes.radius;
  69848. };
  69849. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69850. var shape = impostor.physicsBody.shapes;
  69851. result.x = shape.halfWidth * 2;
  69852. result.y = shape.halfHeight * 2;
  69853. result.z = shape.halfDepth * 2;
  69854. };
  69855. OimoJSPlugin.prototype.dispose = function () {
  69856. this.world.clear();
  69857. };
  69858. return OimoJSPlugin;
  69859. }());
  69860. BABYLON.OimoJSPlugin = OimoJSPlugin;
  69861. })(BABYLON || (BABYLON = {}));
  69862. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  69863. var BABYLON;
  69864. (function (BABYLON) {
  69865. /*
  69866. * Based on jsTGALoader - Javascript loader for TGA file
  69867. * By Vincent Thibault
  69868. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  69869. */
  69870. var TGATools = /** @class */ (function () {
  69871. function TGATools() {
  69872. }
  69873. TGATools.GetTGAHeader = function (data) {
  69874. var offset = 0;
  69875. var header = {
  69876. id_length: data[offset++],
  69877. colormap_type: data[offset++],
  69878. image_type: data[offset++],
  69879. colormap_index: data[offset++] | data[offset++] << 8,
  69880. colormap_length: data[offset++] | data[offset++] << 8,
  69881. colormap_size: data[offset++],
  69882. origin: [
  69883. data[offset++] | data[offset++] << 8,
  69884. data[offset++] | data[offset++] << 8
  69885. ],
  69886. width: data[offset++] | data[offset++] << 8,
  69887. height: data[offset++] | data[offset++] << 8,
  69888. pixel_size: data[offset++],
  69889. flags: data[offset++]
  69890. };
  69891. return header;
  69892. };
  69893. TGATools.UploadContent = function (gl, data) {
  69894. // Not enough data to contain header ?
  69895. if (data.length < 19) {
  69896. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  69897. return;
  69898. }
  69899. // Read Header
  69900. var offset = 18;
  69901. var header = TGATools.GetTGAHeader(data);
  69902. // Assume it's a valid Targa file.
  69903. if (header.id_length + offset > data.length) {
  69904. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  69905. return;
  69906. }
  69907. // Skip not needed data
  69908. offset += header.id_length;
  69909. var use_rle = false;
  69910. var use_pal = false;
  69911. var use_grey = false;
  69912. // Get some informations.
  69913. switch (header.image_type) {
  69914. case TGATools._TYPE_RLE_INDEXED:
  69915. use_rle = true;
  69916. case TGATools._TYPE_INDEXED:
  69917. use_pal = true;
  69918. break;
  69919. case TGATools._TYPE_RLE_RGB:
  69920. use_rle = true;
  69921. case TGATools._TYPE_RGB:
  69922. // use_rgb = true;
  69923. break;
  69924. case TGATools._TYPE_RLE_GREY:
  69925. use_rle = true;
  69926. case TGATools._TYPE_GREY:
  69927. use_grey = true;
  69928. break;
  69929. }
  69930. var pixel_data;
  69931. // var numAlphaBits = header.flags & 0xf;
  69932. var pixel_size = header.pixel_size >> 3;
  69933. var pixel_total = header.width * header.height * pixel_size;
  69934. // Read palettes
  69935. var palettes;
  69936. if (use_pal) {
  69937. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  69938. }
  69939. // Read LRE
  69940. if (use_rle) {
  69941. pixel_data = new Uint8Array(pixel_total);
  69942. var c, count, i;
  69943. var localOffset = 0;
  69944. var pixels = new Uint8Array(pixel_size);
  69945. while (offset < pixel_total && localOffset < pixel_total) {
  69946. c = data[offset++];
  69947. count = (c & 0x7f) + 1;
  69948. // RLE pixels
  69949. if (c & 0x80) {
  69950. // Bind pixel tmp array
  69951. for (i = 0; i < pixel_size; ++i) {
  69952. pixels[i] = data[offset++];
  69953. }
  69954. // Copy pixel array
  69955. for (i = 0; i < count; ++i) {
  69956. pixel_data.set(pixels, localOffset + i * pixel_size);
  69957. }
  69958. localOffset += pixel_size * count;
  69959. }
  69960. else {
  69961. count *= pixel_size;
  69962. for (i = 0; i < count; ++i) {
  69963. pixel_data[localOffset + i] = data[offset++];
  69964. }
  69965. localOffset += count;
  69966. }
  69967. }
  69968. }
  69969. else {
  69970. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  69971. }
  69972. // Load to texture
  69973. var x_start, y_start, x_step, y_step, y_end, x_end;
  69974. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  69975. default:
  69976. case TGATools._ORIGIN_UL:
  69977. x_start = 0;
  69978. x_step = 1;
  69979. x_end = header.width;
  69980. y_start = 0;
  69981. y_step = 1;
  69982. y_end = header.height;
  69983. break;
  69984. case TGATools._ORIGIN_BL:
  69985. x_start = 0;
  69986. x_step = 1;
  69987. x_end = header.width;
  69988. y_start = header.height - 1;
  69989. y_step = -1;
  69990. y_end = -1;
  69991. break;
  69992. case TGATools._ORIGIN_UR:
  69993. x_start = header.width - 1;
  69994. x_step = -1;
  69995. x_end = -1;
  69996. y_start = 0;
  69997. y_step = 1;
  69998. y_end = header.height;
  69999. break;
  70000. case TGATools._ORIGIN_BR:
  70001. x_start = header.width - 1;
  70002. x_step = -1;
  70003. x_end = -1;
  70004. y_start = header.height - 1;
  70005. y_step = -1;
  70006. y_end = -1;
  70007. break;
  70008. }
  70009. // Load the specify method
  70010. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70011. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70012. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70013. };
  70014. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70015. var image = pixel_data, colormap = palettes;
  70016. var width = header.width, height = header.height;
  70017. var color, i = 0, x, y;
  70018. var imageData = new Uint8Array(width * height * 4);
  70019. for (y = y_start; y !== y_end; y += y_step) {
  70020. for (x = x_start; x !== x_end; x += x_step, i++) {
  70021. color = image[i];
  70022. imageData[(x + width * y) * 4 + 3] = 255;
  70023. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70024. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70025. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70026. }
  70027. }
  70028. return imageData;
  70029. };
  70030. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70031. var image = pixel_data;
  70032. var width = header.width, height = header.height;
  70033. var color, i = 0, x, y;
  70034. var imageData = new Uint8Array(width * height * 4);
  70035. for (y = y_start; y !== y_end; y += y_step) {
  70036. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70037. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70038. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70039. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70040. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70041. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70042. }
  70043. }
  70044. return imageData;
  70045. };
  70046. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70047. var image = pixel_data;
  70048. var width = header.width, height = header.height;
  70049. var i = 0, x, y;
  70050. var imageData = new Uint8Array(width * height * 4);
  70051. for (y = y_start; y !== y_end; y += y_step) {
  70052. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70053. imageData[(x + width * y) * 4 + 3] = 255;
  70054. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70055. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70056. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70057. }
  70058. }
  70059. return imageData;
  70060. };
  70061. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70062. var image = pixel_data;
  70063. var width = header.width, height = header.height;
  70064. var i = 0, x, y;
  70065. var imageData = new Uint8Array(width * height * 4);
  70066. for (y = y_start; y !== y_end; y += y_step) {
  70067. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70068. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70069. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70070. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70071. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70072. }
  70073. }
  70074. return imageData;
  70075. };
  70076. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70077. var image = pixel_data;
  70078. var width = header.width, height = header.height;
  70079. var color, i = 0, x, y;
  70080. var imageData = new Uint8Array(width * height * 4);
  70081. for (y = y_start; y !== y_end; y += y_step) {
  70082. for (x = x_start; x !== x_end; x += x_step, i++) {
  70083. color = image[i];
  70084. imageData[(x + width * y) * 4 + 0] = color;
  70085. imageData[(x + width * y) * 4 + 1] = color;
  70086. imageData[(x + width * y) * 4 + 2] = color;
  70087. imageData[(x + width * y) * 4 + 3] = 255;
  70088. }
  70089. }
  70090. return imageData;
  70091. };
  70092. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70093. var image = pixel_data;
  70094. var width = header.width, height = header.height;
  70095. var i = 0, x, y;
  70096. var imageData = new Uint8Array(width * height * 4);
  70097. for (y = y_start; y !== y_end; y += y_step) {
  70098. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70099. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70100. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70101. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70102. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70103. }
  70104. }
  70105. return imageData;
  70106. };
  70107. //private static _TYPE_NO_DATA = 0;
  70108. TGATools._TYPE_INDEXED = 1;
  70109. TGATools._TYPE_RGB = 2;
  70110. TGATools._TYPE_GREY = 3;
  70111. TGATools._TYPE_RLE_INDEXED = 9;
  70112. TGATools._TYPE_RLE_RGB = 10;
  70113. TGATools._TYPE_RLE_GREY = 11;
  70114. TGATools._ORIGIN_MASK = 0x30;
  70115. TGATools._ORIGIN_SHIFT = 0x04;
  70116. TGATools._ORIGIN_BL = 0x00;
  70117. TGATools._ORIGIN_BR = 0x01;
  70118. TGATools._ORIGIN_UL = 0x02;
  70119. TGATools._ORIGIN_UR = 0x03;
  70120. return TGATools;
  70121. }());
  70122. BABYLON.TGATools = TGATools;
  70123. })(BABYLON || (BABYLON = {}));
  70124. //# sourceMappingURL=babylon.tga.js.map
  70125. var BABYLON;
  70126. (function (BABYLON) {
  70127. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70128. // All values and structures referenced from:
  70129. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70130. var DDS_MAGIC = 0x20534444;
  70131. var
  70132. //DDSD_CAPS = 0x1,
  70133. //DDSD_HEIGHT = 0x2,
  70134. //DDSD_WIDTH = 0x4,
  70135. //DDSD_PITCH = 0x8,
  70136. //DDSD_PIXELFORMAT = 0x1000,
  70137. DDSD_MIPMAPCOUNT = 0x20000;
  70138. //DDSD_LINEARSIZE = 0x80000,
  70139. //DDSD_DEPTH = 0x800000;
  70140. // var DDSCAPS_COMPLEX = 0x8,
  70141. // DDSCAPS_MIPMAP = 0x400000,
  70142. // DDSCAPS_TEXTURE = 0x1000;
  70143. var DDSCAPS2_CUBEMAP = 0x200;
  70144. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70145. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70146. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70147. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70148. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70149. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70150. // DDSCAPS2_VOLUME = 0x200000;
  70151. var
  70152. //DDPF_ALPHAPIXELS = 0x1,
  70153. //DDPF_ALPHA = 0x2,
  70154. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70155. //DDPF_YUV = 0x200,
  70156. DDPF_LUMINANCE = 0x20000;
  70157. function FourCCToInt32(value) {
  70158. return value.charCodeAt(0) +
  70159. (value.charCodeAt(1) << 8) +
  70160. (value.charCodeAt(2) << 16) +
  70161. (value.charCodeAt(3) << 24);
  70162. }
  70163. function Int32ToFourCC(value) {
  70164. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70165. }
  70166. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70167. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70168. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70169. var FOURCC_DX10 = FourCCToInt32("DX10");
  70170. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70171. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70172. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70173. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70174. var headerLengthInt = 31; // The header length in 32 bit ints
  70175. // Offsets into the header array
  70176. var off_magic = 0;
  70177. var off_size = 1;
  70178. var off_flags = 2;
  70179. var off_height = 3;
  70180. var off_width = 4;
  70181. var off_mipmapCount = 7;
  70182. var off_pfFlags = 20;
  70183. var off_pfFourCC = 21;
  70184. var off_RGBbpp = 22;
  70185. // var off_RMask = 23;
  70186. // var off_GMask = 24;
  70187. // var off_BMask = 25;
  70188. // var off_AMask = 26;
  70189. // var off_caps1 = 27;
  70190. var off_caps2 = 28;
  70191. // var off_caps3 = 29;
  70192. // var off_caps4 = 30;
  70193. var off_dxgiFormat = 32;
  70194. ;
  70195. var DDSTools = /** @class */ (function () {
  70196. function DDSTools() {
  70197. }
  70198. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70199. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70200. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70201. var mipmapCount = 1;
  70202. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70203. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70204. }
  70205. var fourCC = header[off_pfFourCC];
  70206. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70207. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70208. switch (fourCC) {
  70209. case FOURCC_D3DFMT_R16G16B16A16F:
  70210. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70211. break;
  70212. case FOURCC_D3DFMT_R32G32B32A32F:
  70213. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70214. break;
  70215. case FOURCC_DX10:
  70216. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70217. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70218. break;
  70219. }
  70220. }
  70221. return {
  70222. width: header[off_width],
  70223. height: header[off_height],
  70224. mipmapCount: mipmapCount,
  70225. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70226. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70227. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70228. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70229. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70230. dxgiFormat: dxgiFormat,
  70231. textureType: textureType
  70232. };
  70233. };
  70234. DDSTools._ToHalfFloat = function (value) {
  70235. if (!DDSTools._FloatView) {
  70236. DDSTools._FloatView = new Float32Array(1);
  70237. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70238. }
  70239. DDSTools._FloatView[0] = value;
  70240. var x = DDSTools._Int32View[0];
  70241. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70242. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70243. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70244. /* If zero, or denormal, or exponent underflows too much for a denormal
  70245. * half, return signed zero. */
  70246. if (e < 103) {
  70247. return bits;
  70248. }
  70249. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70250. if (e > 142) {
  70251. bits |= 0x7c00;
  70252. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70253. * not Inf, so make sure we set one mantissa bit too. */
  70254. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70255. return bits;
  70256. }
  70257. /* If exponent underflows but not too much, return a denormal */
  70258. if (e < 113) {
  70259. m |= 0x0800;
  70260. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70261. * to 1, which is OK. */
  70262. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70263. return bits;
  70264. }
  70265. bits |= ((e - 112) << 10) | (m >> 1);
  70266. bits += m & 1;
  70267. return bits;
  70268. };
  70269. DDSTools._FromHalfFloat = function (value) {
  70270. var s = (value & 0x8000) >> 15;
  70271. var e = (value & 0x7C00) >> 10;
  70272. var f = value & 0x03FF;
  70273. if (e === 0) {
  70274. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70275. }
  70276. else if (e == 0x1F) {
  70277. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70278. }
  70279. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70280. };
  70281. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70282. var destArray = new Float32Array(dataLength);
  70283. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70284. var index = 0;
  70285. for (var y = 0; y < height; y++) {
  70286. for (var x = 0; x < width; x++) {
  70287. var srcPos = (x + y * width) * 4;
  70288. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70289. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70290. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70291. if (DDSTools.StoreLODInAlphaChannel) {
  70292. destArray[index + 3] = lod;
  70293. }
  70294. else {
  70295. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70296. }
  70297. index += 4;
  70298. }
  70299. }
  70300. return destArray;
  70301. };
  70302. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70303. if (DDSTools.StoreLODInAlphaChannel) {
  70304. var destArray = new Uint16Array(dataLength);
  70305. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70306. var index = 0;
  70307. for (var y = 0; y < height; y++) {
  70308. for (var x = 0; x < width; x++) {
  70309. var srcPos = (x + y * width) * 4;
  70310. destArray[index] = srcData[srcPos];
  70311. destArray[index + 1] = srcData[srcPos + 1];
  70312. destArray[index + 2] = srcData[srcPos + 2];
  70313. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70314. index += 4;
  70315. }
  70316. }
  70317. return destArray;
  70318. }
  70319. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70320. };
  70321. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70322. if (DDSTools.StoreLODInAlphaChannel) {
  70323. var destArray = new Float32Array(dataLength);
  70324. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70325. var index = 0;
  70326. for (var y = 0; y < height; y++) {
  70327. for (var x = 0; x < width; x++) {
  70328. var srcPos = (x + y * width) * 4;
  70329. destArray[index] = srcData[srcPos];
  70330. destArray[index + 1] = srcData[srcPos + 1];
  70331. destArray[index + 2] = srcData[srcPos + 2];
  70332. destArray[index + 3] = lod;
  70333. index += 4;
  70334. }
  70335. }
  70336. return destArray;
  70337. }
  70338. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70339. };
  70340. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70341. var destArray = new Uint8Array(dataLength);
  70342. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70343. var index = 0;
  70344. for (var y = 0; y < height; y++) {
  70345. for (var x = 0; x < width; x++) {
  70346. var srcPos = (x + y * width) * 4;
  70347. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70348. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70349. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70350. if (DDSTools.StoreLODInAlphaChannel) {
  70351. destArray[index + 3] = lod;
  70352. }
  70353. else {
  70354. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70355. }
  70356. index += 4;
  70357. }
  70358. }
  70359. return destArray;
  70360. };
  70361. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70362. var destArray = new Uint8Array(dataLength);
  70363. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70364. var index = 0;
  70365. for (var y = 0; y < height; y++) {
  70366. for (var x = 0; x < width; x++) {
  70367. var srcPos = (x + y * width) * 4;
  70368. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70369. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70370. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70371. if (DDSTools.StoreLODInAlphaChannel) {
  70372. destArray[index + 3] = lod;
  70373. }
  70374. else {
  70375. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70376. }
  70377. index += 4;
  70378. }
  70379. }
  70380. return destArray;
  70381. };
  70382. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70383. var byteArray = new Uint8Array(dataLength);
  70384. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70385. var index = 0;
  70386. for (var y = 0; y < height; y++) {
  70387. for (var x = 0; x < width; x++) {
  70388. var srcPos = (x + y * width) * 4;
  70389. byteArray[index] = srcData[srcPos + 2];
  70390. byteArray[index + 1] = srcData[srcPos + 1];
  70391. byteArray[index + 2] = srcData[srcPos];
  70392. byteArray[index + 3] = srcData[srcPos + 3];
  70393. index += 4;
  70394. }
  70395. }
  70396. return byteArray;
  70397. };
  70398. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70399. var byteArray = new Uint8Array(dataLength);
  70400. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70401. var index = 0;
  70402. for (var y = 0; y < height; y++) {
  70403. for (var x = 0; x < width; x++) {
  70404. var srcPos = (x + y * width) * 3;
  70405. byteArray[index] = srcData[srcPos + 2];
  70406. byteArray[index + 1] = srcData[srcPos + 1];
  70407. byteArray[index + 2] = srcData[srcPos];
  70408. index += 3;
  70409. }
  70410. }
  70411. return byteArray;
  70412. };
  70413. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70414. var byteArray = new Uint8Array(dataLength);
  70415. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70416. var index = 0;
  70417. for (var y = 0; y < height; y++) {
  70418. for (var x = 0; x < width; x++) {
  70419. var srcPos = (x + y * width);
  70420. byteArray[index] = srcData[srcPos];
  70421. index++;
  70422. }
  70423. }
  70424. return byteArray;
  70425. };
  70426. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70427. if (lodIndex === void 0) { lodIndex = -1; }
  70428. var ext = engine.getCaps().s3tc;
  70429. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70430. var fourCC, width, height, dataLength = 0, dataOffset;
  70431. var byteArray, mipmapCount, mip;
  70432. var internalFormat = 0;
  70433. var format = 0;
  70434. var blockBytes = 1;
  70435. if (header[off_magic] !== DDS_MAGIC) {
  70436. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70437. return;
  70438. }
  70439. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70440. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70441. return;
  70442. }
  70443. if (info.isCompressed && !ext) {
  70444. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70445. return;
  70446. }
  70447. var bpp = header[off_RGBbpp];
  70448. dataOffset = header[off_size] + 4;
  70449. var computeFormats = false;
  70450. if (info.isFourCC) {
  70451. fourCC = header[off_pfFourCC];
  70452. switch (fourCC) {
  70453. case FOURCC_DXT1:
  70454. blockBytes = 8;
  70455. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70456. break;
  70457. case FOURCC_DXT3:
  70458. blockBytes = 16;
  70459. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70460. break;
  70461. case FOURCC_DXT5:
  70462. blockBytes = 16;
  70463. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70464. break;
  70465. case FOURCC_D3DFMT_R16G16B16A16F:
  70466. computeFormats = true;
  70467. break;
  70468. case FOURCC_D3DFMT_R32G32B32A32F:
  70469. computeFormats = true;
  70470. break;
  70471. case FOURCC_DX10:
  70472. // There is an additionnal header so dataOffset need to be changed
  70473. dataOffset += 5 * 4; // 5 uints
  70474. var supported = false;
  70475. switch (info.dxgiFormat) {
  70476. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70477. computeFormats = true;
  70478. supported = true;
  70479. break;
  70480. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70481. info.isRGB = true;
  70482. info.isFourCC = false;
  70483. bpp = 32;
  70484. supported = true;
  70485. break;
  70486. }
  70487. if (supported) {
  70488. break;
  70489. }
  70490. default:
  70491. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70492. return;
  70493. }
  70494. }
  70495. if (computeFormats) {
  70496. format = engine._getWebGLTextureType(info.textureType);
  70497. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70498. }
  70499. mipmapCount = 1;
  70500. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70501. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70502. }
  70503. for (var face = 0; face < faces; face++) {
  70504. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70505. width = header[off_width];
  70506. height = header[off_height];
  70507. for (mip = 0; mip < mipmapCount; ++mip) {
  70508. if (lodIndex === -1 || lodIndex === mip) {
  70509. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70510. var i = (lodIndex === -1) ? mip : 0;
  70511. if (!info.isCompressed && info.isFourCC) {
  70512. dataLength = width * height * 4;
  70513. var floatArray = null;
  70514. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70515. if (bpp === 128) {
  70516. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70517. }
  70518. else if (bpp === 64) {
  70519. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70520. }
  70521. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70522. format = engine._getWebGLTextureType(info.textureType);
  70523. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70524. }
  70525. else {
  70526. if (bpp === 128) {
  70527. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70528. }
  70529. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70530. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70531. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70532. format = engine._getWebGLTextureType(info.textureType);
  70533. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70534. }
  70535. else {
  70536. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70537. }
  70538. }
  70539. if (floatArray) {
  70540. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70541. }
  70542. }
  70543. else if (info.isRGB) {
  70544. if (bpp === 24) {
  70545. dataLength = width * height * 3;
  70546. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70547. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70548. }
  70549. else {
  70550. dataLength = width * height * 4;
  70551. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70552. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70553. }
  70554. }
  70555. else if (info.isLuminance) {
  70556. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70557. var unpaddedRowSize = width;
  70558. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70559. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70560. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70561. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70562. }
  70563. else {
  70564. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70565. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70566. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70567. }
  70568. }
  70569. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70570. width *= 0.5;
  70571. height *= 0.5;
  70572. width = Math.max(1.0, width);
  70573. height = Math.max(1.0, height);
  70574. }
  70575. if (currentFace !== undefined) {
  70576. // Loading a single face
  70577. break;
  70578. }
  70579. }
  70580. };
  70581. DDSTools.StoreLODInAlphaChannel = false;
  70582. return DDSTools;
  70583. }());
  70584. BABYLON.DDSTools = DDSTools;
  70585. })(BABYLON || (BABYLON = {}));
  70586. //# sourceMappingURL=babylon.dds.js.map
  70587. var BABYLON;
  70588. (function (BABYLON) {
  70589. /**
  70590. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70591. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70592. */
  70593. var KhronosTextureContainer = /** @class */ (function () {
  70594. /**
  70595. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70596. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70597. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70598. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70599. */
  70600. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70601. this.arrayBuffer = arrayBuffer;
  70602. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70603. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70604. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70605. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70606. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70607. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70608. BABYLON.Tools.Error("texture missing KTX identifier");
  70609. return;
  70610. }
  70611. // load the reset of the header in native 32 bit int
  70612. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70613. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70614. var oppositeEndianess = header[0] === 0x01020304;
  70615. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70616. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70617. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70618. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70619. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70620. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70621. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70622. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70623. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70624. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70625. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70626. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70627. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70628. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70629. if (this.glType !== 0) {
  70630. BABYLON.Tools.Error("only compressed formats currently supported");
  70631. return;
  70632. }
  70633. else {
  70634. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70635. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70636. }
  70637. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70638. BABYLON.Tools.Error("only 2D textures currently supported");
  70639. return;
  70640. }
  70641. if (this.numberOfArrayElements !== 0) {
  70642. BABYLON.Tools.Error("texture arrays not currently supported");
  70643. return;
  70644. }
  70645. if (this.numberOfFaces !== facesExpected) {
  70646. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70647. return;
  70648. }
  70649. // we now have a completely validated file, so could use existence of loadType as success
  70650. // would need to make this more elaborate & adjust checks above to support more than one load type
  70651. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70652. }
  70653. // not as fast hardware based, but will probably never need to use
  70654. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70655. return ((val & 0xFF) << 24)
  70656. | ((val & 0xFF00) << 8)
  70657. | ((val >> 8) & 0xFF00)
  70658. | ((val >> 24) & 0xFF);
  70659. };
  70660. /**
  70661. * It is assumed that the texture has already been created & is currently bound
  70662. */
  70663. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70664. switch (this.loadType) {
  70665. case KhronosTextureContainer.COMPRESSED_2D:
  70666. this._upload2DCompressedLevels(gl, loadMipmaps);
  70667. break;
  70668. case KhronosTextureContainer.TEX_2D:
  70669. case KhronosTextureContainer.COMPRESSED_3D:
  70670. case KhronosTextureContainer.TEX_3D:
  70671. }
  70672. };
  70673. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70674. // initialize width & height for level 1
  70675. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70676. var width = this.pixelWidth;
  70677. var height = this.pixelHeight;
  70678. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70679. for (var level = 0; level < mipmapCount; level++) {
  70680. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70681. for (var face = 0; face < this.numberOfFaces; face++) {
  70682. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70683. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70684. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70685. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70686. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70687. }
  70688. width = Math.max(1.0, width * 0.5);
  70689. height = Math.max(1.0, height * 0.5);
  70690. }
  70691. };
  70692. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70693. // load types
  70694. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70695. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70696. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  70697. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  70698. return KhronosTextureContainer;
  70699. }());
  70700. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  70701. })(BABYLON || (BABYLON = {}));
  70702. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  70703. var BABYLON;
  70704. (function (BABYLON) {
  70705. var Debug = /** @class */ (function () {
  70706. function Debug() {
  70707. }
  70708. Debug.AxesViewer = /** @class */ (function () {
  70709. function AxesViewer(scene, scaleLines) {
  70710. if (scaleLines === void 0) { scaleLines = 1; }
  70711. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70712. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70713. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70714. this.scaleLines = 1;
  70715. this.scaleLines = scaleLines;
  70716. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  70717. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  70718. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  70719. this._xmesh.renderingGroupId = 2;
  70720. this._ymesh.renderingGroupId = 2;
  70721. this._zmesh.renderingGroupId = 2;
  70722. this._xmesh.material.checkReadyOnlyOnce = true;
  70723. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  70724. this._ymesh.material.checkReadyOnlyOnce = true;
  70725. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  70726. this._zmesh.material.checkReadyOnlyOnce = true;
  70727. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  70728. this.scene = scene;
  70729. }
  70730. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  70731. var scaleLines = this.scaleLines;
  70732. if (this._xmesh) {
  70733. this._xmesh.position.copyFrom(position);
  70734. }
  70735. if (this._ymesh) {
  70736. this._ymesh.position.copyFrom(position);
  70737. }
  70738. if (this._zmesh) {
  70739. this._zmesh.position.copyFrom(position);
  70740. }
  70741. var point2 = this._xline[1];
  70742. point2.x = xaxis.x * scaleLines;
  70743. point2.y = xaxis.y * scaleLines;
  70744. point2.z = xaxis.z * scaleLines;
  70745. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  70746. point2 = this._yline[1];
  70747. point2.x = yaxis.x * scaleLines;
  70748. point2.y = yaxis.y * scaleLines;
  70749. point2.z = yaxis.z * scaleLines;
  70750. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  70751. point2 = this._zline[1];
  70752. point2.x = zaxis.x * scaleLines;
  70753. point2.y = zaxis.y * scaleLines;
  70754. point2.z = zaxis.z * scaleLines;
  70755. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  70756. };
  70757. AxesViewer.prototype.dispose = function () {
  70758. if (this._xmesh) {
  70759. this._xmesh.dispose();
  70760. }
  70761. if (this._ymesh) {
  70762. this._ymesh.dispose();
  70763. }
  70764. if (this._zmesh) {
  70765. this._zmesh.dispose();
  70766. }
  70767. this._xmesh = null;
  70768. this._ymesh = null;
  70769. this._zmesh = null;
  70770. this.scene = null;
  70771. };
  70772. return AxesViewer;
  70773. }());
  70774. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  70775. __extends(BoneAxesViewer, _super);
  70776. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  70777. if (scaleLines === void 0) { scaleLines = 1; }
  70778. var _this = _super.call(this, scene, scaleLines) || this;
  70779. _this.pos = BABYLON.Vector3.Zero();
  70780. _this.xaxis = BABYLON.Vector3.Zero();
  70781. _this.yaxis = BABYLON.Vector3.Zero();
  70782. _this.zaxis = BABYLON.Vector3.Zero();
  70783. _this.mesh = mesh;
  70784. _this.bone = bone;
  70785. return _this;
  70786. }
  70787. BoneAxesViewer.prototype.update = function () {
  70788. if (!this.mesh || !this.bone) {
  70789. return;
  70790. }
  70791. var bone = this.bone;
  70792. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  70793. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  70794. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  70795. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  70796. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  70797. };
  70798. BoneAxesViewer.prototype.dispose = function () {
  70799. if (this.mesh) {
  70800. this.mesh = null;
  70801. this.bone = null;
  70802. _super.prototype.dispose.call(this);
  70803. }
  70804. };
  70805. return BoneAxesViewer;
  70806. }(Debug.AxesViewer));
  70807. Debug.PhysicsViewer = /** @class */ (function () {
  70808. function PhysicsViewer(scene) {
  70809. this._impostors = [];
  70810. this._meshes = [];
  70811. this._numMeshes = 0;
  70812. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70813. var physicEngine = this._scene.getPhysicsEngine();
  70814. if (physicEngine) {
  70815. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  70816. }
  70817. }
  70818. PhysicsViewer.prototype._updateDebugMeshes = function () {
  70819. var plugin = this._physicsEnginePlugin;
  70820. for (var i = 0; i < this._numMeshes; i++) {
  70821. var impostor = this._impostors[i];
  70822. if (!impostor) {
  70823. continue;
  70824. }
  70825. if (impostor.isDisposed) {
  70826. this.hideImpostor(this._impostors[i--]);
  70827. }
  70828. else {
  70829. var mesh = this._meshes[i];
  70830. if (mesh && plugin) {
  70831. plugin.syncMeshWithImpostor(mesh, impostor);
  70832. }
  70833. }
  70834. }
  70835. };
  70836. PhysicsViewer.prototype.showImpostor = function (impostor) {
  70837. if (!this._scene) {
  70838. return;
  70839. }
  70840. for (var i = 0; i < this._numMeshes; i++) {
  70841. if (this._impostors[i] == impostor) {
  70842. return;
  70843. }
  70844. }
  70845. var debugMesh = this._getDebugMesh(impostor, this._scene);
  70846. if (debugMesh) {
  70847. this._impostors[this._numMeshes] = impostor;
  70848. this._meshes[this._numMeshes] = debugMesh;
  70849. if (this._numMeshes === 0) {
  70850. this._renderFunction = this._updateDebugMeshes.bind(this);
  70851. this._scene.registerBeforeRender(this._renderFunction);
  70852. }
  70853. this._numMeshes++;
  70854. }
  70855. };
  70856. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  70857. if (!impostor || !this._scene) {
  70858. return;
  70859. }
  70860. var removed = false;
  70861. for (var i = 0; i < this._numMeshes; i++) {
  70862. if (this._impostors[i] == impostor) {
  70863. var mesh = this._meshes[i];
  70864. if (!mesh) {
  70865. continue;
  70866. }
  70867. this._scene.removeMesh(mesh);
  70868. mesh.dispose();
  70869. this._numMeshes--;
  70870. if (this._numMeshes > 0) {
  70871. this._meshes[i] = this._meshes[this._numMeshes];
  70872. this._impostors[i] = this._impostors[this._numMeshes];
  70873. this._meshes[this._numMeshes] = null;
  70874. this._impostors[this._numMeshes] = null;
  70875. }
  70876. else {
  70877. this._meshes[0] = null;
  70878. this._impostors[0] = null;
  70879. }
  70880. removed = true;
  70881. break;
  70882. }
  70883. }
  70884. if (removed && this._numMeshes === 0) {
  70885. this._scene.unregisterBeforeRender(this._renderFunction);
  70886. }
  70887. };
  70888. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  70889. if (!this._debugMaterial) {
  70890. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  70891. this._debugMaterial.wireframe = true;
  70892. }
  70893. return this._debugMaterial;
  70894. };
  70895. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  70896. if (!this._debugBoxMesh) {
  70897. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  70898. this._debugBoxMesh.renderingGroupId = 1;
  70899. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70900. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  70901. scene.removeMesh(this._debugBoxMesh);
  70902. }
  70903. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  70904. };
  70905. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  70906. if (!this._debugSphereMesh) {
  70907. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  70908. this._debugSphereMesh.renderingGroupId = 1;
  70909. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70910. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  70911. scene.removeMesh(this._debugSphereMesh);
  70912. }
  70913. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  70914. };
  70915. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  70916. var mesh = null;
  70917. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  70918. mesh = this._getDebugBoxMesh(scene);
  70919. impostor.getBoxSizeToRef(mesh.scaling);
  70920. }
  70921. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  70922. mesh = this._getDebugSphereMesh(scene);
  70923. var radius = impostor.getRadius();
  70924. mesh.scaling.x = radius * 2;
  70925. mesh.scaling.y = radius * 2;
  70926. mesh.scaling.z = radius * 2;
  70927. }
  70928. return mesh;
  70929. };
  70930. PhysicsViewer.prototype.dispose = function () {
  70931. for (var i = 0; i < this._numMeshes; i++) {
  70932. this.hideImpostor(this._impostors[i]);
  70933. }
  70934. if (this._debugBoxMesh) {
  70935. this._debugBoxMesh.dispose();
  70936. }
  70937. if (this._debugSphereMesh) {
  70938. this._debugSphereMesh.dispose();
  70939. }
  70940. if (this._debugMaterial) {
  70941. this._debugMaterial.dispose();
  70942. }
  70943. this._impostors.length = 0;
  70944. this._scene = null;
  70945. this._physicsEnginePlugin = null;
  70946. };
  70947. return PhysicsViewer;
  70948. }());
  70949. Debug.SkeletonViewer = /** @class */ (function () {
  70950. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  70951. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  70952. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  70953. this.skeleton = skeleton;
  70954. this.mesh = mesh;
  70955. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  70956. this.renderingGroupId = renderingGroupId;
  70957. this.color = BABYLON.Color3.White();
  70958. this._debugLines = new Array();
  70959. this._isEnabled = false;
  70960. this._scene = scene;
  70961. this.update();
  70962. this._renderFunction = this.update.bind(this);
  70963. }
  70964. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  70965. get: function () {
  70966. return this._isEnabled;
  70967. },
  70968. set: function (value) {
  70969. if (this._isEnabled === value) {
  70970. return;
  70971. }
  70972. this._isEnabled = value;
  70973. if (value) {
  70974. this._scene.registerBeforeRender(this._renderFunction);
  70975. }
  70976. else {
  70977. this._scene.unregisterBeforeRender(this._renderFunction);
  70978. }
  70979. },
  70980. enumerable: true,
  70981. configurable: true
  70982. });
  70983. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  70984. if (x === void 0) { x = 0; }
  70985. if (y === void 0) { y = 0; }
  70986. if (z === void 0) { z = 0; }
  70987. var tmat = BABYLON.Tmp.Matrix[0];
  70988. var parentBone = bone.getParent();
  70989. tmat.copyFrom(bone.getLocalMatrix());
  70990. if (x !== 0 || y !== 0 || z !== 0) {
  70991. var tmat2 = BABYLON.Tmp.Matrix[1];
  70992. BABYLON.Matrix.IdentityToRef(tmat2);
  70993. tmat2.m[12] = x;
  70994. tmat2.m[13] = y;
  70995. tmat2.m[14] = z;
  70996. tmat2.multiplyToRef(tmat, tmat);
  70997. }
  70998. if (parentBone) {
  70999. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71000. }
  71001. tmat.multiplyToRef(meshMat, tmat);
  71002. position.x = tmat.m[12];
  71003. position.y = tmat.m[13];
  71004. position.z = tmat.m[14];
  71005. };
  71006. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71007. var len = bones.length;
  71008. var meshPos = this.mesh.position;
  71009. for (var i = 0; i < len; i++) {
  71010. var bone = bones[i];
  71011. var points = this._debugLines[i];
  71012. if (!points) {
  71013. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71014. this._debugLines[i] = points;
  71015. }
  71016. this._getBonePosition(points[0], bone, meshMat);
  71017. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71018. points[0].subtractInPlace(meshPos);
  71019. points[1].subtractInPlace(meshPos);
  71020. }
  71021. };
  71022. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71023. var len = bones.length;
  71024. var boneNum = 0;
  71025. var meshPos = this.mesh.position;
  71026. for (var i = len - 1; i >= 0; i--) {
  71027. var childBone = bones[i];
  71028. var parentBone = childBone.getParent();
  71029. if (!parentBone) {
  71030. continue;
  71031. }
  71032. var points = this._debugLines[boneNum];
  71033. if (!points) {
  71034. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71035. this._debugLines[boneNum] = points;
  71036. }
  71037. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71038. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71039. points[0].subtractInPlace(meshPos);
  71040. points[1].subtractInPlace(meshPos);
  71041. boneNum++;
  71042. }
  71043. };
  71044. SkeletonViewer.prototype.update = function () {
  71045. if (this.autoUpdateBonesMatrices) {
  71046. this.skeleton.computeAbsoluteTransforms();
  71047. }
  71048. if (this.skeleton.bones[0].length === undefined) {
  71049. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71050. }
  71051. else {
  71052. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71053. }
  71054. if (!this._debugMesh) {
  71055. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71056. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71057. }
  71058. else {
  71059. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71060. }
  71061. this._debugMesh.position.copyFrom(this.mesh.position);
  71062. this._debugMesh.color = this.color;
  71063. };
  71064. SkeletonViewer.prototype.dispose = function () {
  71065. if (this._debugMesh) {
  71066. this.isEnabled = false;
  71067. this._debugMesh.dispose();
  71068. this._debugMesh = null;
  71069. }
  71070. };
  71071. return SkeletonViewer;
  71072. }());
  71073. return Debug;
  71074. }());
  71075. BABYLON.Debug = Debug;
  71076. })(BABYLON || (BABYLON = {}));
  71077. //# sourceMappingURL=babylon.debugModules.js.map
  71078. var BABYLON;
  71079. (function (BABYLON) {
  71080. var RayHelper = /** @class */ (function () {
  71081. function RayHelper(ray) {
  71082. this.ray = ray;
  71083. }
  71084. RayHelper.CreateAndShow = function (ray, scene, color) {
  71085. var helper = new RayHelper(ray);
  71086. helper.show(scene, color);
  71087. return helper;
  71088. };
  71089. RayHelper.prototype.show = function (scene, color) {
  71090. if (!this._renderFunction && this.ray) {
  71091. var ray = this.ray;
  71092. this._renderFunction = this._render.bind(this);
  71093. this._scene = scene;
  71094. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71095. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71096. if (this._renderFunction) {
  71097. this._scene.registerBeforeRender(this._renderFunction);
  71098. }
  71099. }
  71100. if (color && this._renderLine) {
  71101. this._renderLine.color.copyFrom(color);
  71102. }
  71103. };
  71104. RayHelper.prototype.hide = function () {
  71105. if (this._renderFunction && this._scene) {
  71106. this._scene.unregisterBeforeRender(this._renderFunction);
  71107. this._scene = null;
  71108. this._renderFunction = null;
  71109. if (this._renderLine) {
  71110. this._renderLine.dispose();
  71111. this._renderLine = null;
  71112. }
  71113. this._renderPoints = [];
  71114. }
  71115. };
  71116. RayHelper.prototype._render = function () {
  71117. var ray = this.ray;
  71118. if (!ray) {
  71119. return;
  71120. }
  71121. var point = this._renderPoints[1];
  71122. var len = Math.min(ray.length, 1000000);
  71123. point.copyFrom(ray.direction);
  71124. point.scaleInPlace(len);
  71125. point.addInPlace(ray.origin);
  71126. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71127. };
  71128. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71129. this._attachedToMesh = mesh;
  71130. var ray = this.ray;
  71131. if (!ray) {
  71132. return;
  71133. }
  71134. if (!ray.direction) {
  71135. ray.direction = BABYLON.Vector3.Zero();
  71136. }
  71137. if (!ray.origin) {
  71138. ray.origin = BABYLON.Vector3.Zero();
  71139. }
  71140. if (length) {
  71141. ray.length = length;
  71142. }
  71143. if (!meshSpaceOrigin) {
  71144. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71145. }
  71146. if (!meshSpaceDirection) {
  71147. // -1 so that this will work with Mesh.lookAt
  71148. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71149. }
  71150. if (!this._meshSpaceDirection) {
  71151. this._meshSpaceDirection = meshSpaceDirection.clone();
  71152. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71153. }
  71154. else {
  71155. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71156. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71157. }
  71158. if (!this._updateToMeshFunction) {
  71159. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71160. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71161. }
  71162. this._updateToMesh();
  71163. };
  71164. RayHelper.prototype.detachFromMesh = function () {
  71165. if (this._attachedToMesh) {
  71166. if (this._updateToMeshFunction) {
  71167. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71168. }
  71169. this._attachedToMesh = null;
  71170. this._updateToMeshFunction = null;
  71171. }
  71172. };
  71173. RayHelper.prototype._updateToMesh = function () {
  71174. var ray = this.ray;
  71175. if (!this._attachedToMesh || !ray) {
  71176. return;
  71177. }
  71178. if (this._attachedToMesh._isDisposed) {
  71179. this.detachFromMesh();
  71180. return;
  71181. }
  71182. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71183. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71184. };
  71185. RayHelper.prototype.dispose = function () {
  71186. this.hide();
  71187. this.detachFromMesh();
  71188. this.ray = null;
  71189. };
  71190. return RayHelper;
  71191. }());
  71192. BABYLON.RayHelper = RayHelper;
  71193. })(BABYLON || (BABYLON = {}));
  71194. //# sourceMappingURL=babylon.rayHelper.js.map
  71195. var BABYLON;
  71196. (function (BABYLON) {
  71197. // load the inspector using require, if not present in the global namespace.
  71198. var DebugLayer = /** @class */ (function () {
  71199. function DebugLayer(scene) {
  71200. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71201. this._scene = scene;
  71202. // load inspector using require, if it doesn't exist on the global namespace.
  71203. }
  71204. /** Creates the inspector window. */
  71205. DebugLayer.prototype._createInspector = function (config) {
  71206. if (config === void 0) { config = {}; }
  71207. var popup = config.popup || false;
  71208. var initialTab = config.initialTab || 0;
  71209. var parentElement = config.parentElement || null;
  71210. if (!this._inspector) {
  71211. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71212. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71213. } // else nothing to do,; instance is already existing
  71214. };
  71215. DebugLayer.prototype.isVisible = function () {
  71216. if (!this._inspector) {
  71217. return false;
  71218. }
  71219. return true;
  71220. };
  71221. DebugLayer.prototype.hide = function () {
  71222. if (this._inspector) {
  71223. try {
  71224. this._inspector.dispose();
  71225. }
  71226. catch (e) {
  71227. // If the inspector has been removed directly from the inspector tool
  71228. }
  71229. this._inspector = null;
  71230. }
  71231. };
  71232. DebugLayer.prototype.show = function (config) {
  71233. if (config === void 0) { config = {}; }
  71234. if (typeof this.BJSINSPECTOR == 'undefined') {
  71235. // Load inspector and add it to the DOM
  71236. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71237. }
  71238. else {
  71239. // Otherwise creates the inspector
  71240. this._createInspector(config);
  71241. }
  71242. };
  71243. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71244. return DebugLayer;
  71245. }());
  71246. BABYLON.DebugLayer = DebugLayer;
  71247. })(BABYLON || (BABYLON = {}));
  71248. //# sourceMappingURL=babylon.debugLayer.js.map
  71249. var BABYLON;
  71250. (function (BABYLON) {
  71251. var BoundingBoxRenderer = /** @class */ (function () {
  71252. function BoundingBoxRenderer(scene) {
  71253. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71254. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71255. this.showBackLines = true;
  71256. this.renderList = new BABYLON.SmartArray(32);
  71257. this._vertexBuffers = {};
  71258. this._scene = scene;
  71259. }
  71260. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71261. if (this._colorShader) {
  71262. return;
  71263. }
  71264. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71265. attributes: [BABYLON.VertexBuffer.PositionKind],
  71266. uniforms: ["world", "viewProjection", "color"]
  71267. });
  71268. var engine = this._scene.getEngine();
  71269. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71271. this._createIndexBuffer();
  71272. };
  71273. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71274. var engine = this._scene.getEngine();
  71275. 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]);
  71276. };
  71277. BoundingBoxRenderer.prototype._rebuild = function () {
  71278. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71279. if (vb) {
  71280. vb._rebuild();
  71281. }
  71282. this._createIndexBuffer();
  71283. };
  71284. BoundingBoxRenderer.prototype.reset = function () {
  71285. this.renderList.reset();
  71286. };
  71287. BoundingBoxRenderer.prototype.render = function () {
  71288. if (this.renderList.length === 0) {
  71289. return;
  71290. }
  71291. this._prepareRessources();
  71292. if (!this._colorShader.isReady()) {
  71293. return;
  71294. }
  71295. var engine = this._scene.getEngine();
  71296. engine.setDepthWrite(false);
  71297. this._colorShader._preBind();
  71298. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71299. var boundingBox = this.renderList.data[boundingBoxIndex];
  71300. var min = boundingBox.minimum;
  71301. var max = boundingBox.maximum;
  71302. var diff = max.subtract(min);
  71303. var median = min.add(diff.scale(0.5));
  71304. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71305. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71306. .multiply(boundingBox.getWorldMatrix());
  71307. // VBOs
  71308. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71309. if (this.showBackLines) {
  71310. // Back
  71311. engine.setDepthFunctionToGreaterOrEqual();
  71312. this._scene.resetCachedMaterial();
  71313. this._colorShader.setColor4("color", this.backColor.toColor4());
  71314. this._colorShader.bind(worldMatrix);
  71315. // Draw order
  71316. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71317. }
  71318. // Front
  71319. engine.setDepthFunctionToLess();
  71320. this._scene.resetCachedMaterial();
  71321. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71322. this._colorShader.bind(worldMatrix);
  71323. // Draw order
  71324. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71325. }
  71326. this._colorShader.unbind();
  71327. engine.setDepthFunctionToLessOrEqual();
  71328. engine.setDepthWrite(true);
  71329. };
  71330. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71331. this._prepareRessources();
  71332. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71333. return;
  71334. }
  71335. var engine = this._scene.getEngine();
  71336. engine.setDepthWrite(false);
  71337. engine.setColorWrite(false);
  71338. this._colorShader._preBind();
  71339. var boundingBox = mesh._boundingInfo.boundingBox;
  71340. var min = boundingBox.minimum;
  71341. var max = boundingBox.maximum;
  71342. var diff = max.subtract(min);
  71343. var median = min.add(diff.scale(0.5));
  71344. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71345. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71346. .multiply(boundingBox.getWorldMatrix());
  71347. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71348. engine.setDepthFunctionToLess();
  71349. this._scene.resetCachedMaterial();
  71350. this._colorShader.bind(worldMatrix);
  71351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71352. this._colorShader.unbind();
  71353. engine.setDepthFunctionToLessOrEqual();
  71354. engine.setDepthWrite(true);
  71355. engine.setColorWrite(true);
  71356. };
  71357. BoundingBoxRenderer.prototype.dispose = function () {
  71358. if (!this._colorShader) {
  71359. return;
  71360. }
  71361. this.renderList.dispose();
  71362. this._colorShader.dispose();
  71363. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71364. if (buffer) {
  71365. buffer.dispose();
  71366. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71367. }
  71368. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71369. };
  71370. return BoundingBoxRenderer;
  71371. }());
  71372. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71373. })(BABYLON || (BABYLON = {}));
  71374. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71375. var BABYLON;
  71376. (function (BABYLON) {
  71377. var MorphTarget = /** @class */ (function () {
  71378. function MorphTarget(name, influence) {
  71379. if (influence === void 0) { influence = 0; }
  71380. this.name = name;
  71381. this.animations = new Array();
  71382. this._positions = null;
  71383. this._normals = null;
  71384. this._tangents = null;
  71385. this.onInfluenceChanged = new BABYLON.Observable();
  71386. this.influence = influence;
  71387. }
  71388. Object.defineProperty(MorphTarget.prototype, "influence", {
  71389. get: function () {
  71390. return this._influence;
  71391. },
  71392. set: function (influence) {
  71393. if (this._influence === influence) {
  71394. return;
  71395. }
  71396. var previous = this._influence;
  71397. this._influence = influence;
  71398. if (this.onInfluenceChanged.hasObservers) {
  71399. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71400. }
  71401. },
  71402. enumerable: true,
  71403. configurable: true
  71404. });
  71405. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71406. get: function () {
  71407. return !!this._positions;
  71408. },
  71409. enumerable: true,
  71410. configurable: true
  71411. });
  71412. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71413. get: function () {
  71414. return !!this._normals;
  71415. },
  71416. enumerable: true,
  71417. configurable: true
  71418. });
  71419. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71420. get: function () {
  71421. return !!this._tangents;
  71422. },
  71423. enumerable: true,
  71424. configurable: true
  71425. });
  71426. MorphTarget.prototype.setPositions = function (data) {
  71427. this._positions = data;
  71428. };
  71429. MorphTarget.prototype.getPositions = function () {
  71430. return this._positions;
  71431. };
  71432. MorphTarget.prototype.setNormals = function (data) {
  71433. this._normals = data;
  71434. };
  71435. MorphTarget.prototype.getNormals = function () {
  71436. return this._normals;
  71437. };
  71438. MorphTarget.prototype.setTangents = function (data) {
  71439. this._tangents = data;
  71440. };
  71441. MorphTarget.prototype.getTangents = function () {
  71442. return this._tangents;
  71443. };
  71444. /**
  71445. * Serializes the current target into a Serialization object.
  71446. * Returns the serialized object.
  71447. */
  71448. MorphTarget.prototype.serialize = function () {
  71449. var serializationObject = {};
  71450. serializationObject.name = this.name;
  71451. serializationObject.influence = this.influence;
  71452. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71453. if (this.hasNormals) {
  71454. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71455. }
  71456. if (this.hasTangents) {
  71457. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71458. }
  71459. // Animations
  71460. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71461. return serializationObject;
  71462. };
  71463. // Statics
  71464. MorphTarget.Parse = function (serializationObject) {
  71465. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71466. result.setPositions(serializationObject.positions);
  71467. if (serializationObject.normals) {
  71468. result.setNormals(serializationObject.normals);
  71469. }
  71470. if (serializationObject.tangents) {
  71471. result.setTangents(serializationObject.tangents);
  71472. }
  71473. // Animations
  71474. if (serializationObject.animations) {
  71475. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71476. var parsedAnimation = serializationObject.animations[animationIndex];
  71477. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71478. }
  71479. }
  71480. return result;
  71481. };
  71482. MorphTarget.FromMesh = function (mesh, name, influence) {
  71483. if (!name) {
  71484. name = mesh.name;
  71485. }
  71486. var result = new MorphTarget(name, influence);
  71487. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71489. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71490. }
  71491. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71492. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71493. }
  71494. return result;
  71495. };
  71496. return MorphTarget;
  71497. }());
  71498. BABYLON.MorphTarget = MorphTarget;
  71499. })(BABYLON || (BABYLON = {}));
  71500. //# sourceMappingURL=babylon.morphTarget.js.map
  71501. var BABYLON;
  71502. (function (BABYLON) {
  71503. var MorphTargetManager = /** @class */ (function () {
  71504. function MorphTargetManager(scene) {
  71505. if (scene === void 0) { scene = null; }
  71506. this._targets = new Array();
  71507. this._targetObservable = new Array();
  71508. this._activeTargets = new BABYLON.SmartArray(16);
  71509. this._supportsNormals = false;
  71510. this._supportsTangents = false;
  71511. this._vertexCount = 0;
  71512. this._uniqueId = 0;
  71513. this._tempInfluences = new Array();
  71514. if (!scene) {
  71515. scene = BABYLON.Engine.LastCreatedScene;
  71516. }
  71517. this._scene = scene;
  71518. if (this._scene) {
  71519. this._scene.morphTargetManagers.push(this);
  71520. this._uniqueId = this._scene.getUniqueId();
  71521. }
  71522. }
  71523. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71524. get: function () {
  71525. return this._uniqueId;
  71526. },
  71527. enumerable: true,
  71528. configurable: true
  71529. });
  71530. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71531. get: function () {
  71532. return this._vertexCount;
  71533. },
  71534. enumerable: true,
  71535. configurable: true
  71536. });
  71537. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71538. get: function () {
  71539. return this._supportsNormals;
  71540. },
  71541. enumerable: true,
  71542. configurable: true
  71543. });
  71544. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71545. get: function () {
  71546. return this._supportsTangents;
  71547. },
  71548. enumerable: true,
  71549. configurable: true
  71550. });
  71551. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71552. get: function () {
  71553. return this._targets.length;
  71554. },
  71555. enumerable: true,
  71556. configurable: true
  71557. });
  71558. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71559. get: function () {
  71560. return this._activeTargets.length;
  71561. },
  71562. enumerable: true,
  71563. configurable: true
  71564. });
  71565. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71566. get: function () {
  71567. return this._influences;
  71568. },
  71569. enumerable: true,
  71570. configurable: true
  71571. });
  71572. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71573. return this._activeTargets.data[index];
  71574. };
  71575. MorphTargetManager.prototype.getTarget = function (index) {
  71576. return this._targets[index];
  71577. };
  71578. MorphTargetManager.prototype.addTarget = function (target) {
  71579. var _this = this;
  71580. this._targets.push(target);
  71581. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71582. _this._syncActiveTargets(needUpdate);
  71583. }));
  71584. this._syncActiveTargets(true);
  71585. };
  71586. MorphTargetManager.prototype.removeTarget = function (target) {
  71587. var index = this._targets.indexOf(target);
  71588. if (index >= 0) {
  71589. this._targets.splice(index, 1);
  71590. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71591. this._syncActiveTargets(true);
  71592. }
  71593. };
  71594. /**
  71595. * Serializes the current manager into a Serialization object.
  71596. * Returns the serialized object.
  71597. */
  71598. MorphTargetManager.prototype.serialize = function () {
  71599. var serializationObject = {};
  71600. serializationObject.id = this.uniqueId;
  71601. serializationObject.targets = [];
  71602. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71603. var target = _a[_i];
  71604. serializationObject.targets.push(target.serialize());
  71605. }
  71606. return serializationObject;
  71607. };
  71608. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71609. var influenceCount = 0;
  71610. this._activeTargets.reset();
  71611. this._supportsNormals = true;
  71612. this._supportsTangents = true;
  71613. this._vertexCount = 0;
  71614. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71615. var target = _a[_i];
  71616. this._activeTargets.push(target);
  71617. this._tempInfluences[influenceCount++] = target.influence;
  71618. var positions = target.getPositions();
  71619. if (positions) {
  71620. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71621. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71622. var vertexCount = positions.length / 3;
  71623. if (this._vertexCount === 0) {
  71624. this._vertexCount = vertexCount;
  71625. }
  71626. else if (this._vertexCount !== vertexCount) {
  71627. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71628. return;
  71629. }
  71630. }
  71631. }
  71632. if (!this._influences || this._influences.length !== influenceCount) {
  71633. this._influences = new Float32Array(influenceCount);
  71634. }
  71635. for (var index = 0; index < influenceCount; index++) {
  71636. this._influences[index] = this._tempInfluences[index];
  71637. }
  71638. if (needUpdate && this._scene) {
  71639. // Flag meshes as dirty to resync with the active targets
  71640. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71641. var mesh = _c[_b];
  71642. if (mesh.morphTargetManager === this) {
  71643. mesh._syncGeometryWithMorphTargetManager();
  71644. }
  71645. }
  71646. }
  71647. };
  71648. // Statics
  71649. MorphTargetManager.Parse = function (serializationObject, scene) {
  71650. var result = new MorphTargetManager(scene);
  71651. result._uniqueId = serializationObject.id;
  71652. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71653. var targetData = _a[_i];
  71654. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71655. }
  71656. return result;
  71657. };
  71658. return MorphTargetManager;
  71659. }());
  71660. BABYLON.MorphTargetManager = MorphTargetManager;
  71661. })(BABYLON || (BABYLON = {}));
  71662. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71663. var BABYLON;
  71664. (function (BABYLON) {
  71665. var Octree = /** @class */ (function () {
  71666. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71667. if (maxDepth === void 0) { maxDepth = 2; }
  71668. this.maxDepth = maxDepth;
  71669. this.dynamicContent = new Array();
  71670. this._maxBlockCapacity = maxBlockCapacity || 64;
  71671. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71672. this._creationFunc = creationFunc;
  71673. }
  71674. // Methods
  71675. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71676. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71677. };
  71678. Octree.prototype.addMesh = function (entry) {
  71679. for (var index = 0; index < this.blocks.length; index++) {
  71680. var block = this.blocks[index];
  71681. block.addEntry(entry);
  71682. }
  71683. };
  71684. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71685. this._selectionContent.reset();
  71686. for (var index = 0; index < this.blocks.length; index++) {
  71687. var block = this.blocks[index];
  71688. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71689. }
  71690. if (allowDuplicate) {
  71691. this._selectionContent.concat(this.dynamicContent);
  71692. }
  71693. else {
  71694. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71695. }
  71696. return this._selectionContent;
  71697. };
  71698. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  71699. this._selectionContent.reset();
  71700. for (var index = 0; index < this.blocks.length; index++) {
  71701. var block = this.blocks[index];
  71702. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  71703. }
  71704. if (allowDuplicate) {
  71705. this._selectionContent.concat(this.dynamicContent);
  71706. }
  71707. else {
  71708. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71709. }
  71710. return this._selectionContent;
  71711. };
  71712. Octree.prototype.intersectsRay = function (ray) {
  71713. this._selectionContent.reset();
  71714. for (var index = 0; index < this.blocks.length; index++) {
  71715. var block = this.blocks[index];
  71716. block.intersectsRay(ray, this._selectionContent);
  71717. }
  71718. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71719. return this._selectionContent;
  71720. };
  71721. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  71722. target.blocks = new Array();
  71723. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  71724. // Segmenting space
  71725. for (var x = 0; x < 2; x++) {
  71726. for (var y = 0; y < 2; y++) {
  71727. for (var z = 0; z < 2; z++) {
  71728. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  71729. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  71730. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  71731. block.addEntries(entries);
  71732. target.blocks.push(block);
  71733. }
  71734. }
  71735. }
  71736. };
  71737. Octree.CreationFuncForMeshes = function (entry, block) {
  71738. var boundingInfo = entry.getBoundingInfo();
  71739. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  71740. block.entries.push(entry);
  71741. }
  71742. };
  71743. Octree.CreationFuncForSubMeshes = function (entry, block) {
  71744. var boundingInfo = entry.getBoundingInfo();
  71745. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  71746. block.entries.push(entry);
  71747. }
  71748. };
  71749. return Octree;
  71750. }());
  71751. BABYLON.Octree = Octree;
  71752. })(BABYLON || (BABYLON = {}));
  71753. //# sourceMappingURL=babylon.octree.js.map
  71754. var BABYLON;
  71755. (function (BABYLON) {
  71756. var OctreeBlock = /** @class */ (function () {
  71757. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  71758. this.entries = new Array();
  71759. this._boundingVectors = new Array();
  71760. this._capacity = capacity;
  71761. this._depth = depth;
  71762. this._maxDepth = maxDepth;
  71763. this._creationFunc = creationFunc;
  71764. this._minPoint = minPoint;
  71765. this._maxPoint = maxPoint;
  71766. this._boundingVectors.push(minPoint.clone());
  71767. this._boundingVectors.push(maxPoint.clone());
  71768. this._boundingVectors.push(minPoint.clone());
  71769. this._boundingVectors[2].x = maxPoint.x;
  71770. this._boundingVectors.push(minPoint.clone());
  71771. this._boundingVectors[3].y = maxPoint.y;
  71772. this._boundingVectors.push(minPoint.clone());
  71773. this._boundingVectors[4].z = maxPoint.z;
  71774. this._boundingVectors.push(maxPoint.clone());
  71775. this._boundingVectors[5].z = minPoint.z;
  71776. this._boundingVectors.push(maxPoint.clone());
  71777. this._boundingVectors[6].x = minPoint.x;
  71778. this._boundingVectors.push(maxPoint.clone());
  71779. this._boundingVectors[7].y = minPoint.y;
  71780. }
  71781. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  71782. // Property
  71783. get: function () {
  71784. return this._capacity;
  71785. },
  71786. enumerable: true,
  71787. configurable: true
  71788. });
  71789. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  71790. get: function () {
  71791. return this._minPoint;
  71792. },
  71793. enumerable: true,
  71794. configurable: true
  71795. });
  71796. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  71797. get: function () {
  71798. return this._maxPoint;
  71799. },
  71800. enumerable: true,
  71801. configurable: true
  71802. });
  71803. // Methods
  71804. OctreeBlock.prototype.addEntry = function (entry) {
  71805. if (this.blocks) {
  71806. for (var index = 0; index < this.blocks.length; index++) {
  71807. var block = this.blocks[index];
  71808. block.addEntry(entry);
  71809. }
  71810. return;
  71811. }
  71812. this._creationFunc(entry, this);
  71813. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  71814. this.createInnerBlocks();
  71815. }
  71816. };
  71817. OctreeBlock.prototype.addEntries = function (entries) {
  71818. for (var index = 0; index < entries.length; index++) {
  71819. var mesh = entries[index];
  71820. this.addEntry(mesh);
  71821. }
  71822. };
  71823. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  71824. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  71825. if (this.blocks) {
  71826. for (var index = 0; index < this.blocks.length; index++) {
  71827. var block = this.blocks[index];
  71828. block.select(frustumPlanes, selection, allowDuplicate);
  71829. }
  71830. return;
  71831. }
  71832. if (allowDuplicate) {
  71833. selection.concat(this.entries);
  71834. }
  71835. else {
  71836. selection.concatWithNoDuplicate(this.entries);
  71837. }
  71838. }
  71839. };
  71840. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  71841. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  71842. if (this.blocks) {
  71843. for (var index = 0; index < this.blocks.length; index++) {
  71844. var block = this.blocks[index];
  71845. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  71846. }
  71847. return;
  71848. }
  71849. if (allowDuplicate) {
  71850. selection.concat(this.entries);
  71851. }
  71852. else {
  71853. selection.concatWithNoDuplicate(this.entries);
  71854. }
  71855. }
  71856. };
  71857. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  71858. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  71859. if (this.blocks) {
  71860. for (var index = 0; index < this.blocks.length; index++) {
  71861. var block = this.blocks[index];
  71862. block.intersectsRay(ray, selection);
  71863. }
  71864. return;
  71865. }
  71866. selection.concatWithNoDuplicate(this.entries);
  71867. }
  71868. };
  71869. OctreeBlock.prototype.createInnerBlocks = function () {
  71870. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  71871. };
  71872. return OctreeBlock;
  71873. }());
  71874. BABYLON.OctreeBlock = OctreeBlock;
  71875. })(BABYLON || (BABYLON = {}));
  71876. //# sourceMappingURL=babylon.octreeBlock.js.map
  71877. var BABYLON;
  71878. (function (BABYLON) {
  71879. var SIMDVector3 = /** @class */ (function () {
  71880. function SIMDVector3() {
  71881. }
  71882. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  71883. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  71884. };
  71885. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  71886. var m = transformation.m;
  71887. var m0 = SIMD.Float32x4.load(m, 0);
  71888. var m1 = SIMD.Float32x4.load(m, 4);
  71889. var m2 = SIMD.Float32x4.load(m, 8);
  71890. var m3 = SIMD.Float32x4.load(m, 12);
  71891. 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));
  71892. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  71893. result.x = SIMD.Float32x4.extractLane(r, 0);
  71894. result.y = SIMD.Float32x4.extractLane(r, 1);
  71895. result.z = SIMD.Float32x4.extractLane(r, 2);
  71896. };
  71897. return SIMDVector3;
  71898. }());
  71899. var SIMDMatrix = /** @class */ (function () {
  71900. function SIMDMatrix() {
  71901. }
  71902. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  71903. var tm = this.m;
  71904. var om = other.m;
  71905. var m0 = SIMD.Float32x4.load(om, 0);
  71906. var m1 = SIMD.Float32x4.load(om, 4);
  71907. var m2 = SIMD.Float32x4.load(om, 8);
  71908. var m3 = SIMD.Float32x4.load(om, 12);
  71909. for (var i = 0; i < 16; i += 4) {
  71910. 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)))));
  71911. }
  71912. return this;
  71913. };
  71914. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  71915. var src = this.m;
  71916. var dest = other.m;
  71917. // Load the 4 rows
  71918. var src0 = SIMD.Float32x4.load(src, 0);
  71919. var src1 = SIMD.Float32x4.load(src, 4);
  71920. var src2 = SIMD.Float32x4.load(src, 8);
  71921. var src3 = SIMD.Float32x4.load(src, 12);
  71922. // Transpose the source matrix. Sort of. Not a true transpose operation
  71923. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  71924. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  71925. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  71926. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  71927. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  71928. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  71929. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  71930. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  71931. // This is a true transposition, but it will lead to an incorrect result
  71932. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  71933. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  71934. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71935. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71936. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  71937. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  71938. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71939. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71940. // ----
  71941. tmp1 = SIMD.Float32x4.mul(row2, row3);
  71942. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71943. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  71944. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  71945. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71946. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  71947. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  71948. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  71949. // ----
  71950. tmp1 = SIMD.Float32x4.mul(row1, row2);
  71951. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71952. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  71953. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  71954. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71955. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  71956. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  71957. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  71958. // ----
  71959. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  71960. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71961. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  71962. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  71963. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  71964. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71965. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  71966. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  71967. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  71968. // ----
  71969. tmp1 = SIMD.Float32x4.mul(row0, row1);
  71970. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71971. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71972. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  71973. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71974. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71975. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  71976. // ----
  71977. tmp1 = SIMD.Float32x4.mul(row0, row3);
  71978. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71979. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  71980. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  71981. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71982. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  71983. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  71984. // ----
  71985. tmp1 = SIMD.Float32x4.mul(row0, row2);
  71986. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71987. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  71988. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  71989. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71990. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  71991. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  71992. // Compute determinant
  71993. var det = SIMD.Float32x4.mul(row0, minor0);
  71994. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  71995. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  71996. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  71997. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  71998. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  71999. // These shuffles aren't necessary if the faulty transposition is done
  72000. // up at the top of this function.
  72001. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  72002. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  72003. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  72004. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  72005. // Compute final values by multiplying with 1/det
  72006. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  72007. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  72008. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  72009. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  72010. return this;
  72011. };
  72012. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  72013. var out = result.m;
  72014. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  72015. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  72016. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  72017. // cc.kmVec3Subtract(f, pCenter, pEye);
  72018. var f = SIMD.Float32x4.sub(center, eye);
  72019. // cc.kmVec3Normalize(f, f);
  72020. var tmp = SIMD.Float32x4.mul(f, f);
  72021. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72022. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72023. // cc.kmVec3Assign(up, pUp);
  72024. // cc.kmVec3Normalize(up, up);
  72025. tmp = SIMD.Float32x4.mul(up, up);
  72026. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72027. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72028. // cc.kmVec3Cross(s, f, up);
  72029. 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)));
  72030. // cc.kmVec3Normalize(s, s);
  72031. tmp = SIMD.Float32x4.mul(s, s);
  72032. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72033. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72034. // cc.kmVec3Cross(u, s, f);
  72035. 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)));
  72036. // cc.kmVec3Normalize(s, s);
  72037. tmp = SIMD.Float32x4.mul(s, s);
  72038. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72039. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72040. var zero = SIMD.Float32x4.splat(0.0);
  72041. s = SIMD.Float32x4.neg(s);
  72042. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  72043. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  72044. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  72045. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  72046. 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);
  72047. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  72048. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  72049. 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)))));
  72050. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  72051. 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)))));
  72052. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  72053. 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)))));
  72054. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  72055. 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)))));
  72056. };
  72057. return SIMDMatrix;
  72058. }());
  72059. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  72060. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  72061. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  72062. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  72063. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  72064. var SIMDHelper = /** @class */ (function () {
  72065. function SIMDHelper() {
  72066. }
  72067. Object.defineProperty(SIMDHelper, "IsEnabled", {
  72068. get: function () {
  72069. return SIMDHelper._isEnabled;
  72070. },
  72071. enumerable: true,
  72072. configurable: true
  72073. });
  72074. SIMDHelper.DisableSIMD = function () {
  72075. // Replace functions
  72076. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  72077. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  72078. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  72079. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  72080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  72081. SIMDHelper._isEnabled = false;
  72082. };
  72083. SIMDHelper.EnableSIMD = function () {
  72084. if (self.SIMD === undefined) {
  72085. return;
  72086. }
  72087. // check if polyfills needed
  72088. if (!self.Math.fround) {
  72089. self.Math.fround = (function (array) { return function (x) {
  72090. return array[0] = x, array[0];
  72091. }; })(new Float32Array(1));
  72092. }
  72093. if (!self.Math.imul) {
  72094. self.Math.imul = function (a, b) {
  72095. var ah = (a >>> 16) & 0xffff;
  72096. var al = a & 0xffff;
  72097. var bh = (b >>> 16) & 0xffff;
  72098. var bl = b & 0xffff;
  72099. // the shift by 0 fixes the sign on the high part
  72100. // the final |0 converts the unsigned value into a signed value
  72101. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  72102. };
  72103. }
  72104. // Replace functions
  72105. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  72106. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  72107. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  72108. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  72109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  72110. SIMDHelper._isEnabled = true;
  72111. };
  72112. SIMDHelper._isEnabled = false;
  72113. return SIMDHelper;
  72114. }());
  72115. BABYLON.SIMDHelper = SIMDHelper;
  72116. })(BABYLON || (BABYLON = {}));
  72117. //# sourceMappingURL=babylon.math.SIMD.js.map
  72118. var BABYLON;
  72119. (function (BABYLON) {
  72120. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72121. __extends(VRDistortionCorrectionPostProcess, _super);
  72122. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72123. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72124. 'LensCenter',
  72125. 'Scale',
  72126. 'ScaleIn',
  72127. 'HmdWarpParam'
  72128. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72129. _this._isRightEye = isRightEye;
  72130. _this._distortionFactors = vrMetrics.distortionK;
  72131. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72132. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72133. _this.adaptScaleToCurrentViewport = true;
  72134. _this.onSizeChangedObservable.add(function () {
  72135. _this.aspectRatio = _this.width * .5 / _this.height;
  72136. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72137. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72138. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72139. });
  72140. _this.onApplyObservable.add(function (effect) {
  72141. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72142. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72143. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72144. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72145. });
  72146. return _this;
  72147. }
  72148. return VRDistortionCorrectionPostProcess;
  72149. }(BABYLON.PostProcess));
  72150. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72151. })(BABYLON || (BABYLON = {}));
  72152. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72153. var BABYLON;
  72154. (function (BABYLON) {
  72155. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72156. __extends(AnaglyphPostProcess, _super);
  72157. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72158. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72159. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72160. _this.onApplyObservable.add(function (effect) {
  72161. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72162. });
  72163. return _this;
  72164. }
  72165. return AnaglyphPostProcess;
  72166. }(BABYLON.PostProcess));
  72167. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72168. })(BABYLON || (BABYLON = {}));
  72169. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72170. var BABYLON;
  72171. (function (BABYLON) {
  72172. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72173. __extends(StereoscopicInterlacePostProcess, _super);
  72174. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72175. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72176. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72177. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72178. _this.onSizeChangedObservable.add(function () {
  72179. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72180. });
  72181. _this.onApplyObservable.add(function (effect) {
  72182. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72183. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72184. });
  72185. return _this;
  72186. }
  72187. return StereoscopicInterlacePostProcess;
  72188. }(BABYLON.PostProcess));
  72189. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72190. })(BABYLON || (BABYLON = {}));
  72191. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72192. var BABYLON;
  72193. (function (BABYLON) {
  72194. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72195. function FreeCameraDeviceOrientationInput() {
  72196. var _this = this;
  72197. this._screenOrientationAngle = 0;
  72198. this._screenQuaternion = new BABYLON.Quaternion();
  72199. this._alpha = 0;
  72200. this._beta = 0;
  72201. this._gamma = 0;
  72202. this._orientationChanged = function () {
  72203. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72204. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72205. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72206. };
  72207. this._deviceOrientation = function (evt) {
  72208. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72209. _this._beta = evt.beta !== null ? evt.beta : 0;
  72210. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72211. };
  72212. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72213. this._orientationChanged();
  72214. }
  72215. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72216. get: function () {
  72217. return this._camera;
  72218. },
  72219. set: function (camera) {
  72220. this._camera = camera;
  72221. if (this._camera != null && !this._camera.rotationQuaternion) {
  72222. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72223. }
  72224. },
  72225. enumerable: true,
  72226. configurable: true
  72227. });
  72228. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72229. window.addEventListener("orientationchange", this._orientationChanged);
  72230. window.addEventListener("deviceorientation", this._deviceOrientation);
  72231. //In certain cases, the attach control is called AFTER orientation was changed,
  72232. //So this is needed.
  72233. this._orientationChanged();
  72234. };
  72235. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72236. window.removeEventListener("orientationchange", this._orientationChanged);
  72237. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72238. };
  72239. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72240. //if no device orientation provided, don't update the rotation.
  72241. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72242. if (!this._alpha)
  72243. return;
  72244. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72245. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72246. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72247. //Mirror on XY Plane
  72248. this._camera.rotationQuaternion.z *= -1;
  72249. this._camera.rotationQuaternion.w *= -1;
  72250. };
  72251. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72252. return "FreeCameraDeviceOrientationInput";
  72253. };
  72254. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72255. return "deviceOrientation";
  72256. };
  72257. return FreeCameraDeviceOrientationInput;
  72258. }());
  72259. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72260. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72261. })(BABYLON || (BABYLON = {}));
  72262. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72263. var BABYLON;
  72264. (function (BABYLON) {
  72265. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72266. function ArcRotateCameraVRDeviceOrientationInput() {
  72267. this.alphaCorrection = 1;
  72268. this.betaCorrection = 1;
  72269. this.gammaCorrection = 1;
  72270. this._alpha = 0;
  72271. this._gamma = 0;
  72272. this._dirty = false;
  72273. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72274. }
  72275. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72276. this.camera.attachControl(element, noPreventDefault);
  72277. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72278. };
  72279. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72280. if (evt.alpha !== null) {
  72281. this._alpha = +evt.alpha | 0;
  72282. }
  72283. if (evt.gamma !== null) {
  72284. this._gamma = +evt.gamma | 0;
  72285. }
  72286. this._dirty = true;
  72287. };
  72288. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72289. if (this._dirty) {
  72290. this._dirty = false;
  72291. if (this._gamma < 0) {
  72292. this._gamma = 180 + this._gamma;
  72293. }
  72294. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72295. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72296. }
  72297. };
  72298. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72299. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72300. };
  72301. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72302. return "ArcRotateCameraVRDeviceOrientationInput";
  72303. };
  72304. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72305. return "VRDeviceOrientation";
  72306. };
  72307. return ArcRotateCameraVRDeviceOrientationInput;
  72308. }());
  72309. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72310. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72311. })(BABYLON || (BABYLON = {}));
  72312. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72313. var BABYLON;
  72314. (function (BABYLON) {
  72315. var VRCameraMetrics = /** @class */ (function () {
  72316. function VRCameraMetrics() {
  72317. this.compensateDistortion = true;
  72318. }
  72319. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72320. get: function () {
  72321. return this.hResolution / (2 * this.vResolution);
  72322. },
  72323. enumerable: true,
  72324. configurable: true
  72325. });
  72326. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72327. get: function () {
  72328. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72329. },
  72330. enumerable: true,
  72331. configurable: true
  72332. });
  72333. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72334. get: function () {
  72335. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72336. var h = (4 * meters) / this.hScreenSize;
  72337. return BABYLON.Matrix.Translation(h, 0, 0);
  72338. },
  72339. enumerable: true,
  72340. configurable: true
  72341. });
  72342. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72343. get: function () {
  72344. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72345. var h = (4 * meters) / this.hScreenSize;
  72346. return BABYLON.Matrix.Translation(-h, 0, 0);
  72347. },
  72348. enumerable: true,
  72349. configurable: true
  72350. });
  72351. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72352. get: function () {
  72353. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72354. },
  72355. enumerable: true,
  72356. configurable: true
  72357. });
  72358. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72359. get: function () {
  72360. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72361. },
  72362. enumerable: true,
  72363. configurable: true
  72364. });
  72365. VRCameraMetrics.GetDefault = function () {
  72366. var result = new VRCameraMetrics();
  72367. result.hResolution = 1280;
  72368. result.vResolution = 800;
  72369. result.hScreenSize = 0.149759993;
  72370. result.vScreenSize = 0.0935999975;
  72371. result.vScreenCenter = 0.0467999987;
  72372. result.eyeToScreenDistance = 0.0410000011;
  72373. result.lensSeparationDistance = 0.0635000020;
  72374. result.interpupillaryDistance = 0.0640000030;
  72375. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72376. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72377. result.postProcessScaleFactor = 1.714605507808412;
  72378. result.lensCenterOffset = 0.151976421;
  72379. return result;
  72380. };
  72381. return VRCameraMetrics;
  72382. }());
  72383. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72384. })(BABYLON || (BABYLON = {}));
  72385. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72386. var BABYLON;
  72387. (function (BABYLON) {
  72388. var WebVRFreeCamera = /** @class */ (function (_super) {
  72389. __extends(WebVRFreeCamera, _super);
  72390. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72391. if (webVROptions === void 0) { webVROptions = {}; }
  72392. var _this = _super.call(this, name, position, scene) || this;
  72393. _this.webVROptions = webVROptions;
  72394. _this._vrDevice = null;
  72395. _this.rawPose = null;
  72396. _this._specsVersion = "1.1";
  72397. _this._attached = false;
  72398. _this._descendants = [];
  72399. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72400. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72401. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72402. _this._standingMatrix = null;
  72403. // Represents device position and rotation in babylon space
  72404. _this.devicePosition = BABYLON.Vector3.Zero();
  72405. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72406. _this.deviceScaleFactor = 1;
  72407. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72408. _this._worldToDevice = BABYLON.Matrix.Identity();
  72409. _this.controllers = [];
  72410. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72411. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72412. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72413. _this._defaultHeight = 0;
  72414. _this.deviceDistanceToRoomGround = function () {
  72415. if (_this._standingMatrix) {
  72416. // Add standing matrix offset to get real offset from ground in room
  72417. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72418. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72419. }
  72420. else {
  72421. return _this._defaultHeight;
  72422. }
  72423. };
  72424. _this.useStandingMatrix = function (callback) {
  72425. if (callback === void 0) { callback = function (bool) { }; }
  72426. // Use standing matrix if availible
  72427. if (!navigator || !navigator.getVRDisplays) {
  72428. callback(false);
  72429. }
  72430. else {
  72431. navigator.getVRDisplays().then(function (displays) {
  72432. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72433. callback(false);
  72434. }
  72435. else {
  72436. _this._standingMatrix = new BABYLON.Matrix();
  72437. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72438. if (!_this.getScene().useRightHandedSystem) {
  72439. [2, 6, 8, 9, 14].forEach(function (num) {
  72440. if (_this._standingMatrix) {
  72441. _this._standingMatrix.m[num] *= -1;
  72442. }
  72443. });
  72444. }
  72445. callback(true);
  72446. }
  72447. });
  72448. }
  72449. };
  72450. _this._workingVector = BABYLON.Vector3.Zero();
  72451. _this._oneVector = BABYLON.Vector3.One();
  72452. _this._workingMatrix = BABYLON.Matrix.Identity();
  72453. _this._cache.position = BABYLON.Vector3.Zero();
  72454. if (webVROptions.defaultHeight) {
  72455. _this._defaultHeight = webVROptions.defaultHeight;
  72456. _this.position.y = _this._defaultHeight;
  72457. }
  72458. _this.minZ = 0.1;
  72459. //legacy support - the compensation boolean was removed.
  72460. if (arguments.length === 5) {
  72461. _this.webVROptions = arguments[4];
  72462. }
  72463. // default webVR options
  72464. if (_this.webVROptions.trackPosition == undefined) {
  72465. _this.webVROptions.trackPosition = true;
  72466. }
  72467. if (_this.webVROptions.controllerMeshes == undefined) {
  72468. _this.webVROptions.controllerMeshes = true;
  72469. }
  72470. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72471. _this.webVROptions.defaultLightingOnControllers = true;
  72472. }
  72473. _this.rotationQuaternion = new BABYLON.Quaternion();
  72474. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72475. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72476. }
  72477. //enable VR
  72478. var engine = _this.getEngine();
  72479. _this._onVREnabled = function (success) { if (success) {
  72480. _this.initControllers();
  72481. } };
  72482. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72483. engine.initWebVR().add(function (event) {
  72484. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72485. return;
  72486. }
  72487. _this._vrDevice = event.vrDisplay;
  72488. //reset the rig parameters.
  72489. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72490. if (_this._attached) {
  72491. _this.getEngine().enableVR();
  72492. }
  72493. });
  72494. if (typeof (VRFrameData) !== "undefined")
  72495. _this._frameData = new VRFrameData();
  72496. /**
  72497. * The idea behind the following lines:
  72498. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72499. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72500. * the second will not show it correctly.
  72501. *
  72502. * To solve this - each object that has the camera as parent will be added to a protected array.
  72503. * When the rig camera renders, it will take this array and set all of those to be its children.
  72504. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72505. * Amazing!
  72506. */
  72507. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72508. if (camera.parent === _this && _this.rigParenting) {
  72509. _this._descendants = _this.getDescendants(true, function (n) {
  72510. // don't take the cameras or the controllers!
  72511. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72512. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72513. return !isController && !isRigCamera;
  72514. });
  72515. _this._descendants.forEach(function (node) {
  72516. node.parent = camera;
  72517. });
  72518. }
  72519. });
  72520. scene.onAfterCameraRenderObservable.add(function (camera) {
  72521. if (camera.parent === _this && _this.rigParenting) {
  72522. _this._descendants.forEach(function (node) {
  72523. node.parent = _this;
  72524. });
  72525. }
  72526. });
  72527. return _this;
  72528. }
  72529. WebVRFreeCamera.prototype.dispose = function () {
  72530. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72531. _super.prototype.dispose.call(this);
  72532. };
  72533. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72534. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72535. var gp = _a[_i];
  72536. if (gp.hand === name) {
  72537. return gp;
  72538. }
  72539. }
  72540. return null;
  72541. };
  72542. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72543. get: function () {
  72544. if (!this._leftController) {
  72545. this._leftController = this.getControllerByName("left");
  72546. }
  72547. return this._leftController;
  72548. },
  72549. enumerable: true,
  72550. configurable: true
  72551. });
  72552. ;
  72553. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72554. get: function () {
  72555. if (!this._rightController) {
  72556. this._rightController = this.getControllerByName("right");
  72557. }
  72558. return this._rightController;
  72559. },
  72560. enumerable: true,
  72561. configurable: true
  72562. });
  72563. ;
  72564. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72565. if (length === void 0) { length = 100; }
  72566. if (this.leftCamera) {
  72567. // Use left eye to avoid computation to compute center on every call
  72568. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72569. }
  72570. else {
  72571. return _super.prototype.getForwardRay.call(this, length);
  72572. }
  72573. };
  72574. WebVRFreeCamera.prototype._checkInputs = function () {
  72575. if (this._vrDevice && this._vrDevice.isPresenting) {
  72576. this._vrDevice.getFrameData(this._frameData);
  72577. this.updateFromDevice(this._frameData.pose);
  72578. }
  72579. _super.prototype._checkInputs.call(this);
  72580. };
  72581. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72582. if (poseData && poseData.orientation) {
  72583. this.rawPose = poseData;
  72584. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72585. if (this.getScene().useRightHandedSystem) {
  72586. this._deviceRoomRotationQuaternion.z *= -1;
  72587. this._deviceRoomRotationQuaternion.w *= -1;
  72588. }
  72589. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72590. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72591. if (this.getScene().useRightHandedSystem) {
  72592. this._deviceRoomPosition.z *= -1;
  72593. }
  72594. }
  72595. }
  72596. };
  72597. /**
  72598. * WebVR's attach control will start broadcasting frames to the device.
  72599. * Note that in certain browsers (chrome for example) this function must be called
  72600. * within a user-interaction callback. Example:
  72601. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72602. *
  72603. * @param {HTMLElement} element
  72604. * @param {boolean} [noPreventDefault]
  72605. *
  72606. * @memberOf WebVRFreeCamera
  72607. */
  72608. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72609. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72610. this._attached = true;
  72611. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72612. if (this._vrDevice) {
  72613. this.getEngine().enableVR();
  72614. }
  72615. };
  72616. WebVRFreeCamera.prototype.detachControl = function (element) {
  72617. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72618. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72619. _super.prototype.detachControl.call(this, element);
  72620. this._attached = false;
  72621. this.getEngine().disableVR();
  72622. };
  72623. WebVRFreeCamera.prototype.getClassName = function () {
  72624. return "WebVRFreeCamera";
  72625. };
  72626. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72627. //uses the vrDisplay's "resetPose()".
  72628. //pitch and roll won't be affected.
  72629. this._vrDevice.resetPose();
  72630. };
  72631. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72632. var camLeft = this._rigCameras[0];
  72633. var camRight = this._rigCameras[1];
  72634. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72635. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72636. camLeft.position.copyFrom(this._deviceRoomPosition);
  72637. camRight.position.copyFrom(this._deviceRoomPosition);
  72638. };
  72639. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72640. var _this = this;
  72641. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72642. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72643. if (!this.updateCacheCalled) {
  72644. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72645. this.updateCacheCalled = true;
  72646. this.update();
  72647. }
  72648. // Set working vector to the device position in room space rotated by the new rotation
  72649. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72650. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72651. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72652. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72653. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72654. // Add translation from anchor position
  72655. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72656. this._workingVector.addInPlace(this.position);
  72657. this._workingVector.subtractInPlace(this._cache.position);
  72658. this._deviceToWorld.setTranslation(this._workingVector);
  72659. // Set an inverted matrix to be used when updating the camera
  72660. this._deviceToWorld.invertToRef(this._worldToDevice);
  72661. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72662. this.controllers.forEach(function (controller) {
  72663. controller._deviceToWorld = _this._deviceToWorld;
  72664. controller.update();
  72665. });
  72666. }
  72667. if (!ignoreParentClass) {
  72668. _super.prototype._updateCache.call(this);
  72669. }
  72670. this.updateCacheCalled = false;
  72671. };
  72672. WebVRFreeCamera.prototype.update = function () {
  72673. // Get current device position in babylon world
  72674. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72675. // Get current device rotation in babylon world
  72676. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72677. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72678. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72679. _super.prototype.update.call(this);
  72680. };
  72681. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72682. return BABYLON.Matrix.Identity();
  72683. };
  72684. /**
  72685. * This function is called by the two RIG cameras.
  72686. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72687. */
  72688. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72689. var _this = this;
  72690. //WebVR 1.1
  72691. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72692. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72693. if (!this.getScene().useRightHandedSystem) {
  72694. [2, 6, 8, 9, 14].forEach(function (num) {
  72695. _this._webvrViewMatrix.m[num] *= -1;
  72696. });
  72697. }
  72698. // update the camera rotation matrix
  72699. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72700. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72701. // Computing target and final matrix
  72702. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72703. var parentCamera = this._cameraRigParams["parentCamera"];
  72704. // should the view matrix be updated with scale and position offset?
  72705. if (parentCamera.deviceScaleFactor !== 1) {
  72706. this._webvrViewMatrix.invert();
  72707. // scale the position, if set
  72708. if (parentCamera.deviceScaleFactor) {
  72709. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72710. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72711. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72712. }
  72713. this._webvrViewMatrix.invert();
  72714. }
  72715. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72716. return this._webvrViewMatrix;
  72717. };
  72718. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72719. var _this = this;
  72720. var parentCamera = this.parent;
  72721. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72722. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72723. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72724. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72725. //babylon compatible matrix
  72726. if (!this.getScene().useRightHandedSystem) {
  72727. [8, 9, 10, 11].forEach(function (num) {
  72728. _this._projectionMatrix.m[num] *= -1;
  72729. });
  72730. }
  72731. return this._projectionMatrix;
  72732. };
  72733. WebVRFreeCamera.prototype.initControllers = function () {
  72734. var _this = this;
  72735. this.controllers = [];
  72736. var manager = this.getScene().gamepadManager;
  72737. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72738. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72739. var webVrController = gamepad;
  72740. if (webVrController.defaultModel) {
  72741. webVrController.defaultModel.setEnabled(false);
  72742. }
  72743. if (webVrController.hand === "right") {
  72744. _this._rightController = null;
  72745. }
  72746. if (webVrController.hand === "left") {
  72747. _this._rightController = null;
  72748. }
  72749. var controllerIndex = _this.controllers.indexOf(webVrController);
  72750. if (controllerIndex !== -1) {
  72751. _this.controllers.splice(controllerIndex, 1);
  72752. }
  72753. }
  72754. });
  72755. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72756. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72757. var webVrController_1 = gamepad;
  72758. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72759. if (_this.webVROptions.controllerMeshes) {
  72760. if (webVrController_1.defaultModel) {
  72761. webVrController_1.defaultModel.setEnabled(true);
  72762. }
  72763. else {
  72764. // Load the meshes
  72765. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72766. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72767. if (_this.webVROptions.defaultLightingOnControllers) {
  72768. if (!_this._lightOnControllers) {
  72769. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72770. }
  72771. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72772. var children = mesh.getChildren();
  72773. if (children.length !== 0) {
  72774. children.forEach(function (mesh) {
  72775. light.includedOnlyMeshes.push(mesh);
  72776. activateLightOnSubMeshes_1(mesh, light);
  72777. });
  72778. }
  72779. };
  72780. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72781. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72782. }
  72783. });
  72784. }
  72785. }
  72786. webVrController_1.attachToPoseControlledCamera(_this);
  72787. // since this is async - sanity check. Is the controller already stored?
  72788. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72789. //add to the controllers array
  72790. _this.controllers.push(webVrController_1);
  72791. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72792. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72793. // So we're overriding setting left & right manually to be sure
  72794. var firstViveWandDetected = false;
  72795. for (var i = 0; i < _this.controllers.length; i++) {
  72796. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72797. if (!firstViveWandDetected) {
  72798. firstViveWandDetected = true;
  72799. _this.controllers[i].hand = "left";
  72800. }
  72801. else {
  72802. _this.controllers[i].hand = "right";
  72803. }
  72804. }
  72805. }
  72806. //did we find enough controllers? Great! let the developer know.
  72807. if (_this.controllers.length >= 2) {
  72808. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72809. }
  72810. }
  72811. }
  72812. });
  72813. };
  72814. return WebVRFreeCamera;
  72815. }(BABYLON.FreeCamera));
  72816. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72817. })(BABYLON || (BABYLON = {}));
  72818. //# sourceMappingURL=babylon.webVRCamera.js.map
  72819. var BABYLON;
  72820. (function (BABYLON) {
  72821. // We're mainly based on the logic defined into the FreeCamera code
  72822. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72823. __extends(DeviceOrientationCamera, _super);
  72824. function DeviceOrientationCamera(name, position, scene) {
  72825. var _this = _super.call(this, name, position, scene) || this;
  72826. _this._quaternionCache = new BABYLON.Quaternion();
  72827. _this.inputs.addDeviceOrientation();
  72828. return _this;
  72829. }
  72830. DeviceOrientationCamera.prototype.getClassName = function () {
  72831. return "DeviceOrientationCamera";
  72832. };
  72833. DeviceOrientationCamera.prototype._checkInputs = function () {
  72834. _super.prototype._checkInputs.call(this);
  72835. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72836. if (this._initialQuaternion) {
  72837. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72838. }
  72839. };
  72840. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72841. var _this = this;
  72842. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72843. //can only work if this camera has a rotation quaternion already.
  72844. if (!this.rotationQuaternion)
  72845. return;
  72846. if (!this._initialQuaternion) {
  72847. this._initialQuaternion = new BABYLON.Quaternion();
  72848. }
  72849. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72850. ['x', 'y', 'z'].forEach(function (axisName) {
  72851. if (!axis[axisName]) {
  72852. _this._initialQuaternion[axisName] = 0;
  72853. }
  72854. else {
  72855. _this._initialQuaternion[axisName] *= -1;
  72856. }
  72857. });
  72858. this._initialQuaternion.normalize();
  72859. //force rotation update
  72860. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72861. };
  72862. return DeviceOrientationCamera;
  72863. }(BABYLON.FreeCamera));
  72864. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72865. })(BABYLON || (BABYLON = {}));
  72866. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72867. var BABYLON;
  72868. (function (BABYLON) {
  72869. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72870. __extends(VRDeviceOrientationFreeCamera, _super);
  72871. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72872. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72873. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72874. var _this = _super.call(this, name, position, scene) || this;
  72875. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72876. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72877. return _this;
  72878. }
  72879. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72880. return "VRDeviceOrientationFreeCamera";
  72881. };
  72882. return VRDeviceOrientationFreeCamera;
  72883. }(BABYLON.DeviceOrientationCamera));
  72884. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72885. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72886. __extends(VRDeviceOrientationGamepadCamera, _super);
  72887. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72888. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72889. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72890. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72891. _this.inputs.addGamepad();
  72892. return _this;
  72893. }
  72894. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72895. return "VRDeviceOrientationGamepadCamera";
  72896. };
  72897. return VRDeviceOrientationGamepadCamera;
  72898. }(VRDeviceOrientationFreeCamera));
  72899. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72900. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72901. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72902. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72903. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72904. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72905. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72906. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72907. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72908. _this.inputs.addVRDeviceOrientation();
  72909. return _this;
  72910. }
  72911. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72912. return "VRDeviceOrientationArcRotateCamera";
  72913. };
  72914. return VRDeviceOrientationArcRotateCamera;
  72915. }(BABYLON.ArcRotateCamera));
  72916. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72917. })(BABYLON || (BABYLON = {}));
  72918. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72919. var BABYLON;
  72920. (function (BABYLON) {
  72921. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72922. __extends(AnaglyphFreeCamera, _super);
  72923. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72924. var _this = _super.call(this, name, position, scene) || this;
  72925. _this.interaxialDistance = interaxialDistance;
  72926. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72927. return _this;
  72928. }
  72929. AnaglyphFreeCamera.prototype.getClassName = function () {
  72930. return "AnaglyphFreeCamera";
  72931. };
  72932. return AnaglyphFreeCamera;
  72933. }(BABYLON.FreeCamera));
  72934. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72935. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72936. __extends(AnaglyphArcRotateCamera, _super);
  72937. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72938. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72939. _this.interaxialDistance = interaxialDistance;
  72940. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72941. return _this;
  72942. }
  72943. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72944. return "AnaglyphArcRotateCamera";
  72945. };
  72946. return AnaglyphArcRotateCamera;
  72947. }(BABYLON.ArcRotateCamera));
  72948. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72949. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72950. __extends(AnaglyphGamepadCamera, _super);
  72951. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  72952. var _this = _super.call(this, name, position, scene) || this;
  72953. _this.interaxialDistance = interaxialDistance;
  72954. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72955. return _this;
  72956. }
  72957. AnaglyphGamepadCamera.prototype.getClassName = function () {
  72958. return "AnaglyphGamepadCamera";
  72959. };
  72960. return AnaglyphGamepadCamera;
  72961. }(BABYLON.GamepadCamera));
  72962. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  72963. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  72964. __extends(AnaglyphUniversalCamera, _super);
  72965. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  72966. var _this = _super.call(this, name, position, scene) || this;
  72967. _this.interaxialDistance = interaxialDistance;
  72968. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72969. return _this;
  72970. }
  72971. AnaglyphUniversalCamera.prototype.getClassName = function () {
  72972. return "AnaglyphUniversalCamera";
  72973. };
  72974. return AnaglyphUniversalCamera;
  72975. }(BABYLON.UniversalCamera));
  72976. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  72977. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  72978. __extends(StereoscopicFreeCamera, _super);
  72979. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72980. var _this = _super.call(this, name, position, scene) || this;
  72981. _this.interaxialDistance = interaxialDistance;
  72982. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72983. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72984. return _this;
  72985. }
  72986. StereoscopicFreeCamera.prototype.getClassName = function () {
  72987. return "StereoscopicFreeCamera";
  72988. };
  72989. return StereoscopicFreeCamera;
  72990. }(BABYLON.FreeCamera));
  72991. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  72992. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  72993. __extends(StereoscopicArcRotateCamera, _super);
  72994. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  72995. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72996. _this.interaxialDistance = interaxialDistance;
  72997. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72998. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72999. return _this;
  73000. }
  73001. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73002. return "StereoscopicArcRotateCamera";
  73003. };
  73004. return StereoscopicArcRotateCamera;
  73005. }(BABYLON.ArcRotateCamera));
  73006. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73007. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73008. __extends(StereoscopicGamepadCamera, _super);
  73009. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73010. var _this = _super.call(this, name, position, scene) || this;
  73011. _this.interaxialDistance = interaxialDistance;
  73012. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73013. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73014. return _this;
  73015. }
  73016. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73017. return "StereoscopicGamepadCamera";
  73018. };
  73019. return StereoscopicGamepadCamera;
  73020. }(BABYLON.GamepadCamera));
  73021. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73022. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73023. __extends(StereoscopicUniversalCamera, _super);
  73024. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73025. var _this = _super.call(this, name, position, scene) || this;
  73026. _this.interaxialDistance = interaxialDistance;
  73027. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73028. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73029. return _this;
  73030. }
  73031. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73032. return "StereoscopicUniversalCamera";
  73033. };
  73034. return StereoscopicUniversalCamera;
  73035. }(BABYLON.UniversalCamera));
  73036. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73037. })(BABYLON || (BABYLON = {}));
  73038. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73039. var BABYLON;
  73040. (function (BABYLON) {
  73041. var VRExperienceHelper = /** @class */ (function () {
  73042. function VRExperienceHelper(scene, webVROptions) {
  73043. if (webVROptions === void 0) { webVROptions = {}; }
  73044. var _this = this;
  73045. this.webVROptions = webVROptions;
  73046. // Can the system support WebVR, even if a headset isn't plugged in?
  73047. this._webVRsupported = false;
  73048. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73049. this._webVRready = false;
  73050. // Are we waiting for the requestPresent callback to complete?
  73051. this._webVRrequesting = false;
  73052. // Are we presenting to the headset right now?
  73053. this._webVRpresenting = false;
  73054. // Are we presenting in the fullscreen fallback?
  73055. this._fullscreenVRpresenting = false;
  73056. /**
  73057. * Observable raised when entering VR.
  73058. */
  73059. this.onEnteringVRObservable = new BABYLON.Observable();
  73060. /**
  73061. * Observable raised when exiting VR.
  73062. */
  73063. this.onExitingVRObservable = new BABYLON.Observable();
  73064. /**
  73065. * Observable raised when controller mesh is loaded.
  73066. */
  73067. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73068. this._useCustomVRButton = false;
  73069. this._teleportationRequested = false;
  73070. this._teleportationEnabledOnLeftController = false;
  73071. this._teleportationEnabledOnRightController = false;
  73072. this._interactionsEnabledOnLeftController = false;
  73073. this._interactionsEnabledOnRightController = false;
  73074. this._leftControllerReady = false;
  73075. this._rightControllerReady = false;
  73076. this._floorMeshesCollection = [];
  73077. this._teleportationAllowed = false;
  73078. this._rotationAllowed = true;
  73079. this._teleportationRequestInitiated = false;
  73080. this._teleportationBackRequestInitiated = false;
  73081. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73082. this._rotationRightAsked = false;
  73083. this._rotationLeftAsked = false;
  73084. this._isDefaultTeleportationTarget = true;
  73085. this._teleportationFillColor = "#444444";
  73086. this._teleportationBorderColor = "#FFFFFF";
  73087. this._rotationAngle = 0;
  73088. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73089. this._padSensibilityUp = 0.65;
  73090. this._padSensibilityDown = 0.35;
  73091. /**
  73092. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73093. */
  73094. this.onNewMeshSelected = new BABYLON.Observable();
  73095. /**
  73096. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73097. */
  73098. this.onNewMeshPicked = new BABYLON.Observable();
  73099. /**
  73100. * Observable raised before camera teleportation
  73101. */
  73102. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73103. /**
  73104. * Observable raised after camera teleportation
  73105. */
  73106. this.onAfterCameraTeleport = new BABYLON.Observable();
  73107. /**
  73108. * Observable raised when current selected mesh gets unselected
  73109. */
  73110. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73111. /**
  73112. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73113. */
  73114. this.teleportationEnabled = true;
  73115. this._pointerDownOnMeshAsked = false;
  73116. this._isActionableMesh = false;
  73117. this._teleportationInitialized = false;
  73118. this._interactionsEnabled = false;
  73119. this._interactionsRequested = false;
  73120. this._displayGaze = true;
  73121. this._displayLaserPointer = true;
  73122. this._dpadPressed = true;
  73123. this._onResize = function () {
  73124. _this.moveButtonToBottomRight();
  73125. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73126. _this.exitVR();
  73127. }
  73128. };
  73129. this._onFullscreenChange = function () {
  73130. if (document.fullscreen !== undefined) {
  73131. _this._fullscreenVRpresenting = document.fullscreen;
  73132. }
  73133. else if (document.mozFullScreen !== undefined) {
  73134. _this._fullscreenVRpresenting = document.mozFullScreen;
  73135. }
  73136. else if (document.webkitIsFullScreen !== undefined) {
  73137. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73138. }
  73139. else if (document.msIsFullScreen !== undefined) {
  73140. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73141. }
  73142. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73143. _this.exitVR();
  73144. if (!_this._useCustomVRButton) {
  73145. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73146. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73147. }
  73148. }
  73149. };
  73150. this.beforeRender = function () {
  73151. _this._castRayAndSelectObject();
  73152. };
  73153. this._onNewGamepadConnected = function (gamepad) {
  73154. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73155. if (gamepad.leftStick) {
  73156. gamepad.onleftstickchanged(function (stickValues) {
  73157. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73158. // Listening to classic/xbox gamepad only if no VR controller is active
  73159. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73160. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73161. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73162. _this._checkTeleportWithRay(stickValues);
  73163. _this._checkTeleportBackwards(stickValues);
  73164. }
  73165. }
  73166. });
  73167. }
  73168. if (gamepad.rightStick) {
  73169. gamepad.onrightstickchanged(function (stickValues) {
  73170. if (_this._teleportationInitialized) {
  73171. _this._checkRotate(stickValues);
  73172. }
  73173. });
  73174. }
  73175. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73176. gamepad.onbuttondown(function (buttonPressed) {
  73177. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73178. _this._selectionPointerDown();
  73179. }
  73180. });
  73181. gamepad.onbuttonup(function (buttonPressed) {
  73182. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73183. _this._selectionPointerUp();
  73184. }
  73185. });
  73186. }
  73187. }
  73188. else {
  73189. var webVRController = gamepad;
  73190. _this._tryEnableInteractionOnController(webVRController);
  73191. }
  73192. };
  73193. // 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
  73194. this._tryEnableInteractionOnController = function (webVRController) {
  73195. if (webVRController.hand === "left") {
  73196. _this._leftControllerReady = true;
  73197. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73198. _this._enableInteractionOnController(webVRController);
  73199. }
  73200. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73201. _this._enableTeleportationOnController(webVRController);
  73202. }
  73203. }
  73204. if (webVRController.hand === "right") {
  73205. _this._rightControllerReady = true;
  73206. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73207. _this._enableInteractionOnController(webVRController);
  73208. }
  73209. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73210. _this._enableTeleportationOnController(webVRController);
  73211. }
  73212. }
  73213. };
  73214. this._onNewGamepadDisconnected = function (gamepad) {
  73215. if (gamepad instanceof BABYLON.WebVRController) {
  73216. if (gamepad.hand === "left") {
  73217. _this._interactionsEnabledOnLeftController = false;
  73218. _this._teleportationEnabledOnLeftController = false;
  73219. _this._leftControllerReady = false;
  73220. if (_this._leftLaserPointer) {
  73221. _this._leftLaserPointer.dispose();
  73222. }
  73223. }
  73224. if (gamepad.hand === "right") {
  73225. _this._interactionsEnabledOnRightController = false;
  73226. _this._teleportationEnabledOnRightController = false;
  73227. _this._rightControllerReady = false;
  73228. if (_this._rightLaserPointer) {
  73229. _this._rightLaserPointer.dispose();
  73230. }
  73231. }
  73232. }
  73233. };
  73234. this._workingVector = BABYLON.Vector3.Zero();
  73235. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73236. this._workingMatrix = BABYLON.Matrix.Identity();
  73237. this._scene = scene;
  73238. this._canvas = scene.getEngine().getRenderingCanvas();
  73239. // Parse options
  73240. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73241. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73242. }
  73243. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73244. webVROptions.createDeviceOrientationCamera = true;
  73245. }
  73246. if (webVROptions.defaultHeight === undefined) {
  73247. webVROptions.defaultHeight = 1.7;
  73248. }
  73249. if (webVROptions.useCustomVRButton) {
  73250. this._useCustomVRButton = true;
  73251. if (webVROptions.customVRButton) {
  73252. this._btnVR = webVROptions.customVRButton;
  73253. }
  73254. }
  73255. if (webVROptions.rayLength) {
  73256. this._rayLength = webVROptions.rayLength;
  73257. }
  73258. this._defaultHeight = webVROptions.defaultHeight;
  73259. // Set position
  73260. if (this._scene.activeCamera) {
  73261. this._position = this._scene.activeCamera.position.clone();
  73262. }
  73263. else {
  73264. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73265. }
  73266. // Set non-vr camera
  73267. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73268. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73269. // Copy data from existing camera
  73270. if (this._scene.activeCamera) {
  73271. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73272. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73273. // Set rotation from previous camera
  73274. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73275. var targetCamera = this._scene.activeCamera;
  73276. if (targetCamera.rotationQuaternion) {
  73277. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73278. }
  73279. else {
  73280. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73281. }
  73282. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73283. }
  73284. }
  73285. this._scene.activeCamera = this._deviceOrientationCamera;
  73286. if (this._canvas) {
  73287. this._scene.activeCamera.attachControl(this._canvas);
  73288. }
  73289. }
  73290. else {
  73291. this._existingCamera = this._scene.activeCamera;
  73292. }
  73293. // Create VR cameras
  73294. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73295. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73296. }
  73297. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73298. this._webVRCamera.useStandingMatrix();
  73299. // Create default button
  73300. if (!this._useCustomVRButton) {
  73301. this._btnVR = document.createElement("BUTTON");
  73302. this._btnVR.className = "babylonVRicon";
  73303. this._btnVR.id = "babylonVRiconbtn";
  73304. this._btnVR.title = "Click to switch to VR";
  73305. 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) }";
  73306. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73307. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73308. // css += ".babylonVRicon.vrdisplaysupported { }";
  73309. // css += ".babylonVRicon.vrdisplayready { }";
  73310. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73311. var style = document.createElement('style');
  73312. style.appendChild(document.createTextNode(css));
  73313. document.getElementsByTagName('head')[0].appendChild(style);
  73314. this.moveButtonToBottomRight();
  73315. }
  73316. // VR button click event
  73317. if (this._btnVR) {
  73318. this._btnVR.addEventListener("click", function () {
  73319. if (!_this.isInVRMode) {
  73320. _this.enterVR();
  73321. }
  73322. else {
  73323. _this.exitVR();
  73324. }
  73325. });
  73326. }
  73327. // Window events
  73328. window.addEventListener("resize", this._onResize);
  73329. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73330. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73331. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73332. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73333. // Display vr button when headset is connected
  73334. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73335. this.displayVRButton();
  73336. }
  73337. else {
  73338. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73339. if (e.vrDisplay) {
  73340. _this.displayVRButton();
  73341. }
  73342. });
  73343. }
  73344. // Exiting VR mode using 'ESC' key on desktop
  73345. this._onKeyDown = function (event) {
  73346. if (event.keyCode === 27 && _this.isInVRMode) {
  73347. _this.exitVR();
  73348. }
  73349. };
  73350. document.addEventListener("keydown", this._onKeyDown);
  73351. // Exiting VR mode double tapping the touch screen
  73352. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73353. if (_this.isInVRMode) {
  73354. _this.exitVR();
  73355. if (_this._fullscreenVRpresenting) {
  73356. _this._scene.getEngine().switchFullscreen(true);
  73357. }
  73358. }
  73359. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73360. // Listen for WebVR display changes
  73361. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73362. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73363. this._onVRRequestPresentStart = function () {
  73364. _this._webVRrequesting = true;
  73365. _this.updateButtonVisibility();
  73366. };
  73367. this._onVRRequestPresentComplete = function (success) {
  73368. _this._webVRrequesting = false;
  73369. _this.updateButtonVisibility();
  73370. };
  73371. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73372. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73373. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73374. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73375. scene.onDisposeObservable.add(function () {
  73376. _this.dispose();
  73377. });
  73378. // Gamepad connection events
  73379. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73380. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73381. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73382. this.updateButtonVisibility();
  73383. //create easing functions
  73384. this._circleEase = new BABYLON.CircleEase();
  73385. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73386. }
  73387. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73388. /** Return this.onEnteringVRObservable
  73389. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73390. */
  73391. get: function () {
  73392. return this.onEnteringVRObservable;
  73393. },
  73394. enumerable: true,
  73395. configurable: true
  73396. });
  73397. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73398. /** Return this.onExitingVRObservable
  73399. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73400. */
  73401. get: function () {
  73402. return this.onExitingVRObservable;
  73403. },
  73404. enumerable: true,
  73405. configurable: true
  73406. });
  73407. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73408. /** Return this.onControllerMeshLoadedObservable
  73409. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73410. */
  73411. get: function () {
  73412. return this.onControllerMeshLoadedObservable;
  73413. },
  73414. enumerable: true,
  73415. configurable: true
  73416. });
  73417. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73418. get: function () {
  73419. return this._teleportationTarget;
  73420. },
  73421. set: function (value) {
  73422. if (value) {
  73423. value.name = "teleportationTarget";
  73424. this._isDefaultTeleportationTarget = false;
  73425. this._teleportationTarget = value;
  73426. }
  73427. },
  73428. enumerable: true,
  73429. configurable: true
  73430. });
  73431. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73432. get: function () {
  73433. return this._displayGaze;
  73434. },
  73435. set: function (value) {
  73436. this._displayGaze = value;
  73437. if (!value) {
  73438. this._gazeTracker.isVisible = false;
  73439. }
  73440. },
  73441. enumerable: true,
  73442. configurable: true
  73443. });
  73444. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73445. get: function () {
  73446. return this._displayLaserPointer;
  73447. },
  73448. set: function (value) {
  73449. this._displayLaserPointer = value;
  73450. if (!value) {
  73451. if (this._rightLaserPointer) {
  73452. this._rightLaserPointer.isVisible = false;
  73453. }
  73454. if (this._leftLaserPointer) {
  73455. this._leftLaserPointer.isVisible = false;
  73456. }
  73457. }
  73458. else {
  73459. if (this._rightLaserPointer) {
  73460. this._rightLaserPointer.isVisible = true;
  73461. }
  73462. else if (this._leftLaserPointer) {
  73463. this._leftLaserPointer.isVisible = true;
  73464. }
  73465. }
  73466. },
  73467. enumerable: true,
  73468. configurable: true
  73469. });
  73470. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73471. get: function () {
  73472. return this._deviceOrientationCamera;
  73473. },
  73474. enumerable: true,
  73475. configurable: true
  73476. });
  73477. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73478. // Based on the current WebVR support, returns the current VR camera used
  73479. get: function () {
  73480. if (this._webVRready) {
  73481. return this._webVRCamera;
  73482. }
  73483. else {
  73484. return this._scene.activeCamera;
  73485. }
  73486. },
  73487. enumerable: true,
  73488. configurable: true
  73489. });
  73490. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73491. get: function () {
  73492. return this._webVRCamera;
  73493. },
  73494. enumerable: true,
  73495. configurable: true
  73496. });
  73497. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73498. get: function () {
  73499. return this._vrDeviceOrientationCamera;
  73500. },
  73501. enumerable: true,
  73502. configurable: true
  73503. });
  73504. // Raised when one of the controller has loaded successfully its associated default mesh
  73505. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73506. this._tryEnableInteractionOnController(webVRController);
  73507. try {
  73508. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73509. }
  73510. catch (err) {
  73511. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73512. }
  73513. };
  73514. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73515. /**
  73516. * Gets a value indicating if we are currently in VR mode.
  73517. */
  73518. get: function () {
  73519. return this._webVRpresenting || this._fullscreenVRpresenting;
  73520. },
  73521. enumerable: true,
  73522. configurable: true
  73523. });
  73524. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73525. var vrDisplay = this._scene.getEngine().getVRDevice();
  73526. if (vrDisplay) {
  73527. var wasPresenting = this._webVRpresenting;
  73528. // A VR display is connected
  73529. this._webVRpresenting = vrDisplay.isPresenting;
  73530. if (wasPresenting && !this._webVRpresenting)
  73531. this.exitVR();
  73532. }
  73533. else {
  73534. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73535. }
  73536. this.updateButtonVisibility();
  73537. };
  73538. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73539. this._webVRsupported = eventArgs.vrSupported;
  73540. this._webVRready = !!eventArgs.vrDisplay;
  73541. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73542. this.updateButtonVisibility();
  73543. };
  73544. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73545. if (this._canvas && !this._useCustomVRButton) {
  73546. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73547. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73548. }
  73549. };
  73550. VRExperienceHelper.prototype.displayVRButton = function () {
  73551. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73552. document.body.appendChild(this._btnVR);
  73553. this._btnVRDisplayed = true;
  73554. }
  73555. };
  73556. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73557. if (!this._btnVR || this._useCustomVRButton) {
  73558. return;
  73559. }
  73560. this._btnVR.className = "babylonVRicon";
  73561. if (this.isInVRMode) {
  73562. this._btnVR.className += " vrdisplaypresenting";
  73563. }
  73564. else {
  73565. if (this._webVRready)
  73566. this._btnVR.className += " vrdisplayready";
  73567. if (this._webVRsupported)
  73568. this._btnVR.className += " vrdisplaysupported";
  73569. if (this._webVRrequesting)
  73570. this._btnVR.className += " vrdisplayrequesting";
  73571. }
  73572. };
  73573. /**
  73574. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73575. * Otherwise, will use the fullscreen API.
  73576. */
  73577. VRExperienceHelper.prototype.enterVR = function () {
  73578. if (this.onEnteringVRObservable) {
  73579. try {
  73580. this.onEnteringVRObservable.notifyObservers(this);
  73581. }
  73582. catch (err) {
  73583. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73584. }
  73585. }
  73586. if (this._scene.activeCamera) {
  73587. this._position = this._scene.activeCamera.position.clone();
  73588. // make sure that we return to the last active camera
  73589. this._existingCamera = this._scene.activeCamera;
  73590. }
  73591. if (this._webVRrequesting)
  73592. return;
  73593. // If WebVR is supported and a headset is connected
  73594. if (this._webVRready) {
  73595. if (!this._webVRpresenting) {
  73596. this._webVRCamera.position = this._position;
  73597. this._scene.activeCamera = this._webVRCamera;
  73598. }
  73599. }
  73600. else if (this._vrDeviceOrientationCamera) {
  73601. this._vrDeviceOrientationCamera.position = this._position;
  73602. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73603. this._scene.getEngine().switchFullscreen(true);
  73604. this.updateButtonVisibility();
  73605. }
  73606. if (this._scene.activeCamera && this._canvas) {
  73607. this._scene.activeCamera.attachControl(this._canvas);
  73608. }
  73609. if (this._interactionsEnabled) {
  73610. this._scene.registerBeforeRender(this.beforeRender);
  73611. }
  73612. };
  73613. /**
  73614. * Attempt to exit VR, or fullscreen.
  73615. */
  73616. VRExperienceHelper.prototype.exitVR = function () {
  73617. if (this.onExitingVRObservable) {
  73618. try {
  73619. this.onExitingVRObservable.notifyObservers(this);
  73620. }
  73621. catch (err) {
  73622. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73623. }
  73624. }
  73625. if (this._webVRpresenting) {
  73626. this._scene.getEngine().disableVR();
  73627. }
  73628. if (this._scene.activeCamera) {
  73629. this._position = this._scene.activeCamera.position.clone();
  73630. }
  73631. if (this._deviceOrientationCamera) {
  73632. this._deviceOrientationCamera.position = this._position;
  73633. this._scene.activeCamera = this._deviceOrientationCamera;
  73634. if (this._canvas) {
  73635. this._scene.activeCamera.attachControl(this._canvas);
  73636. }
  73637. }
  73638. else if (this._existingCamera) {
  73639. this._existingCamera.position = this._position;
  73640. this._scene.activeCamera = this._existingCamera;
  73641. }
  73642. this.updateButtonVisibility();
  73643. if (this._interactionsEnabled) {
  73644. this._scene.unregisterBeforeRender(this.beforeRender);
  73645. }
  73646. };
  73647. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73648. get: function () {
  73649. return this._position;
  73650. },
  73651. set: function (value) {
  73652. this._position = value;
  73653. if (this._scene.activeCamera) {
  73654. this._scene.activeCamera.position = value;
  73655. }
  73656. },
  73657. enumerable: true,
  73658. configurable: true
  73659. });
  73660. VRExperienceHelper.prototype.enableInteractions = function () {
  73661. var _this = this;
  73662. if (!this._interactionsEnabled) {
  73663. this._interactionsRequested = true;
  73664. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73665. this._enableInteractionOnController(this._webVRCamera.leftController);
  73666. }
  73667. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73668. this._enableInteractionOnController(this._webVRCamera.rightController);
  73669. }
  73670. this._createGazeTracker();
  73671. this.raySelectionPredicate = function (mesh) {
  73672. return mesh.isVisible;
  73673. };
  73674. this.meshSelectionPredicate = function (mesh) {
  73675. return true;
  73676. };
  73677. this._raySelectionPredicate = function (mesh) {
  73678. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73679. && mesh.name.indexOf("teleportationTarget") === -1
  73680. && mesh.name.indexOf("torusTeleportation") === -1
  73681. && mesh.name.indexOf("laserPointer") === -1)) {
  73682. return _this.raySelectionPredicate(mesh);
  73683. }
  73684. return false;
  73685. };
  73686. this._interactionsEnabled = true;
  73687. }
  73688. };
  73689. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73690. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73691. if (this._floorMeshesCollection[i].id === mesh.id) {
  73692. return true;
  73693. }
  73694. }
  73695. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73696. return true;
  73697. }
  73698. return false;
  73699. };
  73700. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73701. if (!this._floorMeshesCollection) {
  73702. return;
  73703. }
  73704. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73705. return;
  73706. }
  73707. this._floorMeshesCollection.push(floorMesh);
  73708. };
  73709. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73710. if (!this._floorMeshesCollection) {
  73711. return;
  73712. }
  73713. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73714. if (meshIndex !== -1) {
  73715. this._floorMeshesCollection.splice(meshIndex, 1);
  73716. }
  73717. };
  73718. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73719. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73720. if (!this._teleportationInitialized) {
  73721. this._teleportationRequested = true;
  73722. this.enableInteractions();
  73723. if (vrTeleportationOptions.floorMeshName) {
  73724. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73725. }
  73726. if (vrTeleportationOptions.floorMeshes) {
  73727. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73728. }
  73729. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73730. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73731. }
  73732. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73733. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73734. }
  73735. // Creates an image processing post process for the vignette not relying
  73736. // on the main scene configuration for image processing to reduce setup and spaces
  73737. // (gamma/linear) conflicts.
  73738. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73739. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73740. imageProcessingConfiguration.vignetteEnabled = true;
  73741. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73742. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73743. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73744. this._teleportationInitialized = true;
  73745. if (this._isDefaultTeleportationTarget) {
  73746. this._createTeleportationCircles();
  73747. }
  73748. }
  73749. };
  73750. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73751. var _this = this;
  73752. var controllerMesh = webVRController.mesh;
  73753. if (controllerMesh) {
  73754. var makeNotPick = function (root) {
  73755. root.name += " laserPointer";
  73756. root.getChildMeshes().forEach(function (c) {
  73757. makeNotPick(c);
  73758. });
  73759. };
  73760. makeNotPick(controllerMesh);
  73761. var childMeshes = controllerMesh.getChildMeshes();
  73762. for (var i = 0; i < childMeshes.length; i++) {
  73763. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73764. controllerMesh = childMeshes[i];
  73765. break;
  73766. }
  73767. }
  73768. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73769. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73770. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73771. laserPointerMaterial.alpha = 0.6;
  73772. laserPointer.material = laserPointerMaterial;
  73773. laserPointer.rotation.x = Math.PI / 2;
  73774. laserPointer.parent = controllerMesh;
  73775. laserPointer.position.z = -0.5;
  73776. laserPointer.isVisible = false;
  73777. if (webVRController.hand === "left") {
  73778. this._leftLaserPointer = laserPointer;
  73779. this._interactionsEnabledOnLeftController = true;
  73780. if (!this._rightLaserPointer) {
  73781. this._leftLaserPointer.isVisible = true;
  73782. }
  73783. }
  73784. else {
  73785. this._rightLaserPointer = laserPointer;
  73786. this._interactionsEnabledOnRightController = true;
  73787. if (!this._leftLaserPointer) {
  73788. this._rightLaserPointer.isVisible = true;
  73789. }
  73790. }
  73791. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73792. // Enabling / disabling laserPointer
  73793. if (_this._displayLaserPointer && stateObject.value === 1) {
  73794. laserPointer.isVisible = !laserPointer.isVisible;
  73795. // Laser pointer can only be active on left or right, not both at the same time
  73796. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73797. _this._rightLaserPointer.isVisible = false;
  73798. }
  73799. else if (_this._leftLaserPointer) {
  73800. _this._leftLaserPointer.isVisible = false;
  73801. }
  73802. }
  73803. });
  73804. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73805. if (!_this._pointerDownOnMeshAsked) {
  73806. if (stateObject.value > _this._padSensibilityUp) {
  73807. _this._selectionPointerDown();
  73808. }
  73809. }
  73810. else if (stateObject.value < _this._padSensibilityDown) {
  73811. _this._selectionPointerUp();
  73812. }
  73813. });
  73814. }
  73815. };
  73816. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73817. if (webVRController === void 0) { webVRController = null; }
  73818. if (!this._teleportationRequestInitiated) {
  73819. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73820. if (webVRController) {
  73821. // If laser pointer wasn't enabled yet
  73822. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73823. this._leftLaserPointer.isVisible = true;
  73824. if (this._rightLaserPointer) {
  73825. this._rightLaserPointer.isVisible = false;
  73826. }
  73827. }
  73828. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73829. this._rightLaserPointer.isVisible = true;
  73830. if (this._leftLaserPointer) {
  73831. this._leftLaserPointer.isVisible = false;
  73832. }
  73833. }
  73834. }
  73835. this._teleportationRequestInitiated = true;
  73836. }
  73837. }
  73838. else {
  73839. // Listening to the proper controller values changes to confirm teleportation
  73840. if (webVRController == null
  73841. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73842. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73843. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73844. if (this._teleportationAllowed) {
  73845. this._teleportationAllowed = false;
  73846. this._teleportCamera();
  73847. }
  73848. this._teleportationRequestInitiated = false;
  73849. }
  73850. }
  73851. }
  73852. };
  73853. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73854. this._pointerDownOnMeshAsked = true;
  73855. if (this._currentMeshSelected && this._currentHit) {
  73856. this._scene.simulatePointerDown(this._currentHit);
  73857. }
  73858. };
  73859. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73860. if (this._currentMeshSelected && this._currentHit) {
  73861. this._scene.simulatePointerUp(this._currentHit);
  73862. }
  73863. this._pointerDownOnMeshAsked = false;
  73864. };
  73865. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73866. // Only rotate when user is not currently selecting a teleportation location
  73867. if (this._teleportationRequestInitiated) {
  73868. return;
  73869. }
  73870. if (!this._rotationLeftAsked) {
  73871. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73872. this._rotationLeftAsked = true;
  73873. if (this._rotationAllowed) {
  73874. this._rotateCamera(false);
  73875. }
  73876. }
  73877. }
  73878. else {
  73879. if (stateObject.x > -this._padSensibilityDown) {
  73880. this._rotationLeftAsked = false;
  73881. }
  73882. }
  73883. if (!this._rotationRightAsked) {
  73884. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73885. this._rotationRightAsked = true;
  73886. if (this._rotationAllowed) {
  73887. this._rotateCamera(true);
  73888. }
  73889. }
  73890. }
  73891. else {
  73892. if (stateObject.x < this._padSensibilityDown) {
  73893. this._rotationRightAsked = false;
  73894. }
  73895. }
  73896. };
  73897. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73898. // Only teleport backwards when user is not currently selecting a teleportation location
  73899. if (this._teleportationRequestInitiated) {
  73900. return;
  73901. }
  73902. // Teleport backwards
  73903. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73904. if (!this._teleportationBackRequestInitiated) {
  73905. if (!this.currentVRCamera) {
  73906. return;
  73907. }
  73908. // Get rotation and position of the current camera
  73909. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73910. var position = this.currentVRCamera.position;
  73911. // If the camera has device position, use that instead
  73912. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73913. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73914. position = this.currentVRCamera.devicePosition;
  73915. }
  73916. // Get matrix with only the y rotation of the device rotation
  73917. rotation.toEulerAnglesToRef(this._workingVector);
  73918. this._workingVector.z = 0;
  73919. this._workingVector.x = 0;
  73920. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73921. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73922. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73923. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73924. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73925. var ray = new BABYLON.Ray(position, this._workingVector);
  73926. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73927. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73928. this._teleportCamera(hit.pickedPoint);
  73929. }
  73930. this._teleportationBackRequestInitiated = true;
  73931. }
  73932. }
  73933. else {
  73934. this._teleportationBackRequestInitiated = false;
  73935. }
  73936. };
  73937. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73938. var _this = this;
  73939. var controllerMesh = webVRController.mesh;
  73940. if (controllerMesh) {
  73941. if (webVRController.hand === "left") {
  73942. if (!this._interactionsEnabledOnLeftController) {
  73943. this._enableInteractionOnController(webVRController);
  73944. }
  73945. this._teleportationEnabledOnLeftController = true;
  73946. }
  73947. else {
  73948. if (!this._interactionsEnabledOnRightController) {
  73949. this._enableInteractionOnController(webVRController);
  73950. }
  73951. this._teleportationEnabledOnRightController = true;
  73952. }
  73953. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73954. this._dpadPressed = false;
  73955. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  73956. _this._dpadPressed = stateObject.pressed;
  73957. if (!_this._dpadPressed) {
  73958. _this._rotationLeftAsked = false;
  73959. _this._rotationRightAsked = false;
  73960. _this._teleportationBackRequestInitiated = false;
  73961. }
  73962. });
  73963. }
  73964. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  73965. if (_this.teleportationEnabled) {
  73966. _this._checkTeleportBackwards(stateObject);
  73967. _this._checkTeleportWithRay(stateObject, webVRController);
  73968. }
  73969. _this._checkRotate(stateObject);
  73970. });
  73971. }
  73972. };
  73973. // Gaze support used to point to teleport or to interact with an object
  73974. VRExperienceHelper.prototype._createGazeTracker = function () {
  73975. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  73976. this._gazeTracker.bakeCurrentTransformIntoVertices();
  73977. this._gazeTracker.isPickable = false;
  73978. this._gazeTracker.isVisible = false;
  73979. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  73980. targetMat.specularColor = BABYLON.Color3.Black();
  73981. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73982. targetMat.backFaceCulling = false;
  73983. this._gazeTracker.material = targetMat;
  73984. };
  73985. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  73986. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  73987. this._teleportationTarget.isPickable = false;
  73988. var length = 512;
  73989. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  73990. dynamicTexture.hasAlpha = true;
  73991. var context = dynamicTexture.getContext();
  73992. var centerX = length / 2;
  73993. var centerY = length / 2;
  73994. var radius = 200;
  73995. context.beginPath();
  73996. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  73997. context.fillStyle = this._teleportationFillColor;
  73998. context.fill();
  73999. context.lineWidth = 10;
  74000. context.strokeStyle = this._teleportationBorderColor;
  74001. context.stroke();
  74002. context.closePath();
  74003. dynamicTexture.update();
  74004. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74005. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74006. this._teleportationTarget.material = teleportationCircleMaterial;
  74007. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74008. torus.isPickable = false;
  74009. torus.parent = this._teleportationTarget;
  74010. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74011. var keys = [];
  74012. keys.push({
  74013. frame: 0,
  74014. value: 0
  74015. });
  74016. keys.push({
  74017. frame: 30,
  74018. value: 0.4
  74019. });
  74020. keys.push({
  74021. frame: 60,
  74022. value: 0
  74023. });
  74024. animationInnerCircle.setKeys(keys);
  74025. var easingFunction = new BABYLON.SineEase();
  74026. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74027. animationInnerCircle.setEasingFunction(easingFunction);
  74028. torus.animations = [];
  74029. torus.animations.push(animationInnerCircle);
  74030. this._scene.beginAnimation(torus, 0, 60, true);
  74031. this._hideTeleportationTarget();
  74032. };
  74033. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74034. if (this._teleportationInitialized) {
  74035. this._teleportationTarget.isVisible = true;
  74036. if (this._isDefaultTeleportationTarget) {
  74037. this._teleportationTarget.getChildren()[0].isVisible = true;
  74038. }
  74039. }
  74040. };
  74041. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74042. if (this._teleportationInitialized) {
  74043. this._teleportationTarget.isVisible = false;
  74044. if (this._isDefaultTeleportationTarget) {
  74045. this._teleportationTarget.getChildren()[0].isVisible = false;
  74046. }
  74047. }
  74048. };
  74049. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74050. var _this = this;
  74051. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74052. return;
  74053. }
  74054. if (right) {
  74055. this._rotationAngle++;
  74056. }
  74057. else {
  74058. this._rotationAngle--;
  74059. }
  74060. this.currentVRCamera.animations = [];
  74061. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74062. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74063. var animationRotationKeys = [];
  74064. animationRotationKeys.push({
  74065. frame: 0,
  74066. value: this.currentVRCamera.rotationQuaternion
  74067. });
  74068. animationRotationKeys.push({
  74069. frame: 6,
  74070. value: target
  74071. });
  74072. animationRotation.setKeys(animationRotationKeys);
  74073. animationRotation.setEasingFunction(this._circleEase);
  74074. this.currentVRCamera.animations.push(animationRotation);
  74075. this._postProcessMove.animations = [];
  74076. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74077. var vignetteWeightKeys = [];
  74078. vignetteWeightKeys.push({
  74079. frame: 0,
  74080. value: 0
  74081. });
  74082. vignetteWeightKeys.push({
  74083. frame: 3,
  74084. value: 4
  74085. });
  74086. vignetteWeightKeys.push({
  74087. frame: 6,
  74088. value: 0
  74089. });
  74090. animationPP.setKeys(vignetteWeightKeys);
  74091. animationPP.setEasingFunction(this._circleEase);
  74092. this._postProcessMove.animations.push(animationPP);
  74093. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74094. var vignetteStretchKeys = [];
  74095. vignetteStretchKeys.push({
  74096. frame: 0,
  74097. value: 0
  74098. });
  74099. vignetteStretchKeys.push({
  74100. frame: 3,
  74101. value: 10
  74102. });
  74103. vignetteStretchKeys.push({
  74104. frame: 6,
  74105. value: 0
  74106. });
  74107. animationPP2.setKeys(vignetteStretchKeys);
  74108. animationPP2.setEasingFunction(this._circleEase);
  74109. this._postProcessMove.animations.push(animationPP2);
  74110. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74111. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74112. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74113. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74114. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74115. });
  74116. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74117. };
  74118. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74119. if (hit.pickedPoint) {
  74120. this._teleportationAllowed = true;
  74121. if (this._teleportationRequestInitiated) {
  74122. this._displayTeleportationTarget();
  74123. }
  74124. else {
  74125. this._hideTeleportationTarget();
  74126. }
  74127. this._haloCenter.copyFrom(hit.pickedPoint);
  74128. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74129. var pickNormal = hit.getNormal(true, false);
  74130. if (pickNormal) {
  74131. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74132. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74133. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74134. }
  74135. this._teleportationTarget.position.y += 0.1;
  74136. }
  74137. };
  74138. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74139. var _this = this;
  74140. if (location === void 0) { location = null; }
  74141. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74142. return;
  74143. }
  74144. if (!location) {
  74145. location = this._haloCenter;
  74146. }
  74147. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74148. // offset of the headset from the anchor.
  74149. if (this.webVRCamera.leftCamera) {
  74150. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74151. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74152. location.subtractToRef(this._workingVector, this._workingVector);
  74153. }
  74154. else {
  74155. this._workingVector.copyFrom(location);
  74156. }
  74157. // Add height to account for user's height offset
  74158. if (this.isInVRMode) {
  74159. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74160. }
  74161. else {
  74162. this._workingVector.y += this._defaultHeight;
  74163. }
  74164. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74165. // Create animation from the camera's position to the new location
  74166. this.currentVRCamera.animations = [];
  74167. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74168. var animationCameraTeleportationKeys = [{
  74169. frame: 0,
  74170. value: this.currentVRCamera.position
  74171. },
  74172. {
  74173. frame: 11,
  74174. value: this._workingVector
  74175. }
  74176. ];
  74177. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74178. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74179. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74180. this._postProcessMove.animations = [];
  74181. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74182. var vignetteWeightKeys = [];
  74183. vignetteWeightKeys.push({
  74184. frame: 0,
  74185. value: 0
  74186. });
  74187. vignetteWeightKeys.push({
  74188. frame: 5,
  74189. value: 8
  74190. });
  74191. vignetteWeightKeys.push({
  74192. frame: 11,
  74193. value: 0
  74194. });
  74195. animationPP.setKeys(vignetteWeightKeys);
  74196. this._postProcessMove.animations.push(animationPP);
  74197. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74198. var vignetteStretchKeys = [];
  74199. vignetteStretchKeys.push({
  74200. frame: 0,
  74201. value: 0
  74202. });
  74203. vignetteStretchKeys.push({
  74204. frame: 5,
  74205. value: 10
  74206. });
  74207. vignetteStretchKeys.push({
  74208. frame: 11,
  74209. value: 0
  74210. });
  74211. animationPP2.setKeys(vignetteStretchKeys);
  74212. this._postProcessMove.animations.push(animationPP2);
  74213. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74214. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74215. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74216. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74217. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74218. });
  74219. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74220. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74221. });
  74222. };
  74223. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74224. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74225. return;
  74226. }
  74227. var ray;
  74228. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74229. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74230. }
  74231. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74232. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74233. }
  74234. else {
  74235. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74236. }
  74237. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74238. // Moving the gazeTracker on the mesh face targetted
  74239. if (hit && hit.pickedPoint) {
  74240. if (this._displayGaze) {
  74241. var multiplier = 1;
  74242. this._gazeTracker.isVisible = true;
  74243. if (this._isActionableMesh) {
  74244. multiplier = 3;
  74245. }
  74246. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74247. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74248. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74249. var pickNormal = hit.getNormal();
  74250. // To avoid z-fighting
  74251. var deltaFighting = 0.002;
  74252. if (pickNormal) {
  74253. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74254. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74255. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74256. }
  74257. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74258. if (this._gazeTracker.position.x < 0) {
  74259. this._gazeTracker.position.x += deltaFighting;
  74260. }
  74261. else {
  74262. this._gazeTracker.position.x -= deltaFighting;
  74263. }
  74264. if (this._gazeTracker.position.y < 0) {
  74265. this._gazeTracker.position.y += deltaFighting;
  74266. }
  74267. else {
  74268. this._gazeTracker.position.y -= deltaFighting;
  74269. }
  74270. if (this._gazeTracker.position.z < 0) {
  74271. this._gazeTracker.position.z += deltaFighting;
  74272. }
  74273. else {
  74274. this._gazeTracker.position.z -= deltaFighting;
  74275. }
  74276. }
  74277. // Changing the size of the laser pointer based on the distance from the targetted point
  74278. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74279. this._rightLaserPointer.scaling.y = hit.distance;
  74280. this._rightLaserPointer.position.z = -hit.distance / 2;
  74281. }
  74282. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74283. this._leftLaserPointer.scaling.y = hit.distance;
  74284. this._leftLaserPointer.position.z = -hit.distance / 2;
  74285. }
  74286. }
  74287. else {
  74288. this._gazeTracker.isVisible = false;
  74289. }
  74290. if (hit && hit.pickedMesh) {
  74291. this._currentHit = hit;
  74292. if (this._pointerDownOnMeshAsked) {
  74293. this._scene.simulatePointerMove(this._currentHit);
  74294. }
  74295. // The object selected is the floor, we're in a teleportation scenario
  74296. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74297. // Moving the teleportation area to this targetted point
  74298. this._moveTeleportationSelectorTo(hit);
  74299. return;
  74300. }
  74301. // If not, we're in a selection scenario
  74302. this._hideTeleportationTarget();
  74303. this._teleportationAllowed = false;
  74304. if (hit.pickedMesh !== this._currentMeshSelected) {
  74305. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74306. this.onNewMeshPicked.notifyObservers(hit);
  74307. this._currentMeshSelected = hit.pickedMesh;
  74308. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74309. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74310. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74311. this._isActionableMesh = true;
  74312. }
  74313. else {
  74314. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74315. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74316. this._isActionableMesh = false;
  74317. }
  74318. try {
  74319. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74320. }
  74321. catch (err) {
  74322. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74323. }
  74324. }
  74325. else {
  74326. if (this._currentMeshSelected) {
  74327. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74328. }
  74329. this._currentMeshSelected = null;
  74330. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74331. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74332. }
  74333. }
  74334. }
  74335. else {
  74336. this._currentHit = null;
  74337. this._currentMeshSelected = null;
  74338. this._teleportationAllowed = false;
  74339. this._hideTeleportationTarget();
  74340. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74341. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74342. }
  74343. };
  74344. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74345. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74346. this._leftLaserPointer.material.emissiveColor = color;
  74347. }
  74348. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74349. this._rightLaserPointer.material.emissiveColor = color;
  74350. }
  74351. };
  74352. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74353. if (this._gazeTracker.material) {
  74354. this._gazeTracker.material.emissiveColor = color;
  74355. }
  74356. };
  74357. VRExperienceHelper.prototype.dispose = function () {
  74358. if (this.isInVRMode) {
  74359. this.exitVR();
  74360. }
  74361. if (this._passProcessMove) {
  74362. this._passProcessMove.dispose();
  74363. }
  74364. if (this._postProcessMove) {
  74365. this._postProcessMove.dispose();
  74366. }
  74367. if (this._webVRCamera) {
  74368. this._webVRCamera.dispose();
  74369. }
  74370. if (this._vrDeviceOrientationCamera) {
  74371. this._vrDeviceOrientationCamera.dispose();
  74372. }
  74373. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74374. document.body.removeChild(this._btnVR);
  74375. }
  74376. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74377. this._deviceOrientationCamera.dispose();
  74378. }
  74379. if (this._gazeTracker) {
  74380. this._gazeTracker.dispose();
  74381. }
  74382. if (this._teleportationTarget) {
  74383. this._teleportationTarget.dispose();
  74384. }
  74385. this._floorMeshesCollection = [];
  74386. document.removeEventListener("keydown", this._onKeyDown);
  74387. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74388. window.removeEventListener("resize", this._onResize);
  74389. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74390. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74391. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74392. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74393. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74394. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74395. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74396. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74397. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74398. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74399. this._scene.unregisterBeforeRender(this.beforeRender);
  74400. };
  74401. VRExperienceHelper.prototype.getClassName = function () {
  74402. return "VRExperienceHelper";
  74403. };
  74404. return VRExperienceHelper;
  74405. }());
  74406. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74407. })(BABYLON || (BABYLON = {}));
  74408. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74409. // Mainly based on these 2 articles :
  74410. // 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
  74411. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74412. var BABYLON;
  74413. (function (BABYLON) {
  74414. var JoystickAxis;
  74415. (function (JoystickAxis) {
  74416. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74417. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74418. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74419. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74420. var VirtualJoystick = /** @class */ (function () {
  74421. function VirtualJoystick(leftJoystick) {
  74422. var _this = this;
  74423. if (leftJoystick) {
  74424. this._leftJoystick = true;
  74425. }
  74426. else {
  74427. this._leftJoystick = false;
  74428. }
  74429. VirtualJoystick._globalJoystickIndex++;
  74430. // By default left & right arrow keys are moving the X
  74431. // and up & down keys are moving the Y
  74432. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74433. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74434. this.reverseLeftRight = false;
  74435. this.reverseUpDown = false;
  74436. // collections of pointers
  74437. this._touches = new BABYLON.StringDictionary();
  74438. this.deltaPosition = BABYLON.Vector3.Zero();
  74439. this._joystickSensibility = 25;
  74440. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74441. this._onResize = function (evt) {
  74442. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74443. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74444. if (VirtualJoystick.vjCanvas) {
  74445. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74446. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74447. }
  74448. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74449. };
  74450. // injecting a canvas element on top of the canvas 3D game
  74451. if (!VirtualJoystick.vjCanvas) {
  74452. window.addEventListener("resize", this._onResize, false);
  74453. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74454. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74455. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74456. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74457. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74458. VirtualJoystick.vjCanvas.style.width = "100%";
  74459. VirtualJoystick.vjCanvas.style.height = "100%";
  74460. VirtualJoystick.vjCanvas.style.position = "absolute";
  74461. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74462. VirtualJoystick.vjCanvas.style.top = "0px";
  74463. VirtualJoystick.vjCanvas.style.left = "0px";
  74464. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74465. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74466. // Support for jQuery PEP polyfill
  74467. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74468. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74469. if (!context) {
  74470. throw new Error("Unable to create canvas for virtual joystick");
  74471. }
  74472. VirtualJoystick.vjCanvasContext = context;
  74473. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74474. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74475. document.body.appendChild(VirtualJoystick.vjCanvas);
  74476. }
  74477. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74478. this.pressed = false;
  74479. // default joystick color
  74480. this._joystickColor = "cyan";
  74481. this._joystickPointerID = -1;
  74482. // current joystick position
  74483. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74484. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74485. // origin joystick position
  74486. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74487. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74488. this._onPointerDownHandlerRef = function (evt) {
  74489. _this._onPointerDown(evt);
  74490. };
  74491. this._onPointerMoveHandlerRef = function (evt) {
  74492. _this._onPointerMove(evt);
  74493. };
  74494. this._onPointerUpHandlerRef = function (evt) {
  74495. _this._onPointerUp(evt);
  74496. };
  74497. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74498. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74499. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74500. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74501. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74502. evt.preventDefault(); // Disables system menu
  74503. }, false);
  74504. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74505. }
  74506. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74507. this._joystickSensibility = newJoystickSensibility;
  74508. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74509. };
  74510. VirtualJoystick.prototype._onPointerDown = function (e) {
  74511. var positionOnScreenCondition;
  74512. e.preventDefault();
  74513. if (this._leftJoystick === true) {
  74514. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74515. }
  74516. else {
  74517. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74518. }
  74519. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74520. // First contact will be dedicated to the virtual joystick
  74521. this._joystickPointerID = e.pointerId;
  74522. this._joystickPointerStartPos.x = e.clientX;
  74523. this._joystickPointerStartPos.y = e.clientY;
  74524. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74525. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74526. this._deltaJoystickVector.x = 0;
  74527. this._deltaJoystickVector.y = 0;
  74528. this.pressed = true;
  74529. this._touches.add(e.pointerId.toString(), e);
  74530. }
  74531. else {
  74532. // You can only trigger the action buttons with a joystick declared
  74533. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74534. this._action();
  74535. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74536. }
  74537. }
  74538. };
  74539. VirtualJoystick.prototype._onPointerMove = function (e) {
  74540. // If the current pointer is the one associated to the joystick (first touch contact)
  74541. if (this._joystickPointerID == e.pointerId) {
  74542. this._joystickPointerPos.x = e.clientX;
  74543. this._joystickPointerPos.y = e.clientY;
  74544. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74545. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74546. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74547. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74548. switch (this._axisTargetedByLeftAndRight) {
  74549. case JoystickAxis.X:
  74550. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74551. break;
  74552. case JoystickAxis.Y:
  74553. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74554. break;
  74555. case JoystickAxis.Z:
  74556. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74557. break;
  74558. }
  74559. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74560. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74561. switch (this._axisTargetedByUpAndDown) {
  74562. case JoystickAxis.X:
  74563. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74564. break;
  74565. case JoystickAxis.Y:
  74566. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74567. break;
  74568. case JoystickAxis.Z:
  74569. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74570. break;
  74571. }
  74572. }
  74573. else {
  74574. var data = this._touches.get(e.pointerId.toString());
  74575. if (data) {
  74576. data.x = e.clientX;
  74577. data.y = e.clientY;
  74578. }
  74579. }
  74580. };
  74581. VirtualJoystick.prototype._onPointerUp = function (e) {
  74582. if (this._joystickPointerID == e.pointerId) {
  74583. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74584. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74585. this._joystickPointerID = -1;
  74586. this.pressed = false;
  74587. }
  74588. else {
  74589. var touch = this._touches.get(e.pointerId.toString());
  74590. if (touch) {
  74591. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74592. }
  74593. }
  74594. this._deltaJoystickVector.x = 0;
  74595. this._deltaJoystickVector.y = 0;
  74596. this._touches.remove(e.pointerId.toString());
  74597. };
  74598. /**
  74599. * Change the color of the virtual joystick
  74600. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74601. */
  74602. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74603. this._joystickColor = newColor;
  74604. };
  74605. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74606. this._action = action;
  74607. };
  74608. // Define which axis you'd like to control for left & right
  74609. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74610. switch (axis) {
  74611. case JoystickAxis.X:
  74612. case JoystickAxis.Y:
  74613. case JoystickAxis.Z:
  74614. this._axisTargetedByLeftAndRight = axis;
  74615. break;
  74616. default:
  74617. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74618. break;
  74619. }
  74620. };
  74621. // Define which axis you'd like to control for up & down
  74622. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74623. switch (axis) {
  74624. case JoystickAxis.X:
  74625. case JoystickAxis.Y:
  74626. case JoystickAxis.Z:
  74627. this._axisTargetedByUpAndDown = axis;
  74628. break;
  74629. default:
  74630. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74631. break;
  74632. }
  74633. };
  74634. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74635. var _this = this;
  74636. if (this.pressed) {
  74637. this._touches.forEach(function (key, touch) {
  74638. if (touch.pointerId === _this._joystickPointerID) {
  74639. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74640. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74641. VirtualJoystick.vjCanvasContext.beginPath();
  74642. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74643. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74644. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74645. VirtualJoystick.vjCanvasContext.stroke();
  74646. VirtualJoystick.vjCanvasContext.closePath();
  74647. VirtualJoystick.vjCanvasContext.beginPath();
  74648. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74649. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74650. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74651. VirtualJoystick.vjCanvasContext.stroke();
  74652. VirtualJoystick.vjCanvasContext.closePath();
  74653. VirtualJoystick.vjCanvasContext.beginPath();
  74654. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74655. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74656. VirtualJoystick.vjCanvasContext.stroke();
  74657. VirtualJoystick.vjCanvasContext.closePath();
  74658. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74659. }
  74660. else {
  74661. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74662. VirtualJoystick.vjCanvasContext.beginPath();
  74663. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74664. VirtualJoystick.vjCanvasContext.beginPath();
  74665. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74666. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74667. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74668. VirtualJoystick.vjCanvasContext.stroke();
  74669. VirtualJoystick.vjCanvasContext.closePath();
  74670. touch.prevX = touch.x;
  74671. touch.prevY = touch.y;
  74672. }
  74673. ;
  74674. });
  74675. }
  74676. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74677. };
  74678. VirtualJoystick.prototype.releaseCanvas = function () {
  74679. if (VirtualJoystick.vjCanvas) {
  74680. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74681. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74682. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74683. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74684. window.removeEventListener("resize", this._onResize);
  74685. document.body.removeChild(VirtualJoystick.vjCanvas);
  74686. VirtualJoystick.vjCanvas = null;
  74687. }
  74688. };
  74689. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74690. VirtualJoystick._globalJoystickIndex = 0;
  74691. return VirtualJoystick;
  74692. }());
  74693. BABYLON.VirtualJoystick = VirtualJoystick;
  74694. })(BABYLON || (BABYLON = {}));
  74695. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74696. var BABYLON;
  74697. (function (BABYLON) {
  74698. // We're mainly based on the logic defined into the FreeCamera code
  74699. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74700. __extends(VirtualJoysticksCamera, _super);
  74701. function VirtualJoysticksCamera(name, position, scene) {
  74702. var _this = _super.call(this, name, position, scene) || this;
  74703. _this.inputs.addVirtualJoystick();
  74704. return _this;
  74705. }
  74706. VirtualJoysticksCamera.prototype.getClassName = function () {
  74707. return "VirtualJoysticksCamera";
  74708. };
  74709. return VirtualJoysticksCamera;
  74710. }(BABYLON.FreeCamera));
  74711. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74712. })(BABYLON || (BABYLON = {}));
  74713. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74714. var BABYLON;
  74715. (function (BABYLON) {
  74716. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74717. function FreeCameraVirtualJoystickInput() {
  74718. }
  74719. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74720. return this._leftjoystick;
  74721. };
  74722. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74723. return this._rightjoystick;
  74724. };
  74725. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74726. if (this._leftjoystick) {
  74727. var camera = this.camera;
  74728. var speed = camera._computeLocalCameraSpeed() * 50;
  74729. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74730. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74731. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74732. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74733. if (!this._leftjoystick.pressed) {
  74734. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74735. }
  74736. if (!this._rightjoystick.pressed) {
  74737. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74738. }
  74739. }
  74740. };
  74741. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74742. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74743. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74744. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74745. this._leftjoystick.setJoystickSensibility(0.15);
  74746. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74747. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74748. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74749. this._rightjoystick.reverseUpDown = true;
  74750. this._rightjoystick.setJoystickSensibility(0.05);
  74751. this._rightjoystick.setJoystickColor("yellow");
  74752. };
  74753. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74754. this._leftjoystick.releaseCanvas();
  74755. this._rightjoystick.releaseCanvas();
  74756. };
  74757. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74758. return "FreeCameraVirtualJoystickInput";
  74759. };
  74760. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74761. return "virtualJoystick";
  74762. };
  74763. return FreeCameraVirtualJoystickInput;
  74764. }());
  74765. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74766. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74767. })(BABYLON || (BABYLON = {}));
  74768. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74769. var BABYLON;
  74770. (function (BABYLON) {
  74771. var SimplificationSettings = /** @class */ (function () {
  74772. function SimplificationSettings(quality, distance, optimizeMesh) {
  74773. this.quality = quality;
  74774. this.distance = distance;
  74775. this.optimizeMesh = optimizeMesh;
  74776. }
  74777. return SimplificationSettings;
  74778. }());
  74779. BABYLON.SimplificationSettings = SimplificationSettings;
  74780. var SimplificationQueue = /** @class */ (function () {
  74781. function SimplificationQueue() {
  74782. this.running = false;
  74783. this._simplificationArray = [];
  74784. }
  74785. SimplificationQueue.prototype.addTask = function (task) {
  74786. this._simplificationArray.push(task);
  74787. };
  74788. SimplificationQueue.prototype.executeNext = function () {
  74789. var task = this._simplificationArray.pop();
  74790. if (task) {
  74791. this.running = true;
  74792. this.runSimplification(task);
  74793. }
  74794. else {
  74795. this.running = false;
  74796. }
  74797. };
  74798. SimplificationQueue.prototype.runSimplification = function (task) {
  74799. var _this = this;
  74800. if (task.parallelProcessing) {
  74801. //parallel simplifier
  74802. task.settings.forEach(function (setting) {
  74803. var simplifier = _this.getSimplifier(task);
  74804. simplifier.simplify(setting, function (newMesh) {
  74805. task.mesh.addLODLevel(setting.distance, newMesh);
  74806. newMesh.isVisible = true;
  74807. //check if it is the last
  74808. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74809. //all done, run the success callback.
  74810. task.successCallback();
  74811. }
  74812. _this.executeNext();
  74813. });
  74814. });
  74815. }
  74816. else {
  74817. //single simplifier.
  74818. var simplifier = this.getSimplifier(task);
  74819. var runDecimation = function (setting, callback) {
  74820. simplifier.simplify(setting, function (newMesh) {
  74821. task.mesh.addLODLevel(setting.distance, newMesh);
  74822. newMesh.isVisible = true;
  74823. //run the next quality level
  74824. callback();
  74825. });
  74826. };
  74827. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74828. runDecimation(task.settings[loop.index], function () {
  74829. loop.executeNext();
  74830. });
  74831. }, function () {
  74832. //execution ended, run the success callback.
  74833. if (task.successCallback) {
  74834. task.successCallback();
  74835. }
  74836. _this.executeNext();
  74837. });
  74838. }
  74839. };
  74840. SimplificationQueue.prototype.getSimplifier = function (task) {
  74841. switch (task.simplificationType) {
  74842. case SimplificationType.QUADRATIC:
  74843. default:
  74844. return new QuadraticErrorSimplification(task.mesh);
  74845. }
  74846. };
  74847. return SimplificationQueue;
  74848. }());
  74849. BABYLON.SimplificationQueue = SimplificationQueue;
  74850. /**
  74851. * The implemented types of simplification.
  74852. * At the moment only Quadratic Error Decimation is implemented.
  74853. */
  74854. var SimplificationType;
  74855. (function (SimplificationType) {
  74856. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74857. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74858. var DecimationTriangle = /** @class */ (function () {
  74859. function DecimationTriangle(vertices) {
  74860. this.vertices = vertices;
  74861. this.error = new Array(4);
  74862. this.deleted = false;
  74863. this.isDirty = false;
  74864. this.deletePending = false;
  74865. this.borderFactor = 0;
  74866. }
  74867. return DecimationTriangle;
  74868. }());
  74869. BABYLON.DecimationTriangle = DecimationTriangle;
  74870. var DecimationVertex = /** @class */ (function () {
  74871. function DecimationVertex(position, id) {
  74872. this.position = position;
  74873. this.id = id;
  74874. this.isBorder = true;
  74875. this.q = new QuadraticMatrix();
  74876. this.triangleCount = 0;
  74877. this.triangleStart = 0;
  74878. this.originalOffsets = [];
  74879. }
  74880. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74881. this.position.copyFrom(newPosition);
  74882. };
  74883. return DecimationVertex;
  74884. }());
  74885. BABYLON.DecimationVertex = DecimationVertex;
  74886. var QuadraticMatrix = /** @class */ (function () {
  74887. function QuadraticMatrix(data) {
  74888. this.data = new Array(10);
  74889. for (var i = 0; i < 10; ++i) {
  74890. if (data && data[i]) {
  74891. this.data[i] = data[i];
  74892. }
  74893. else {
  74894. this.data[i] = 0;
  74895. }
  74896. }
  74897. }
  74898. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74899. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74900. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74901. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74902. return det;
  74903. };
  74904. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74905. for (var i = 0; i < 10; ++i) {
  74906. this.data[i] += matrix.data[i];
  74907. }
  74908. };
  74909. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74910. for (var i = 0; i < 10; ++i) {
  74911. this.data[i] += data[i];
  74912. }
  74913. };
  74914. QuadraticMatrix.prototype.add = function (matrix) {
  74915. var m = new QuadraticMatrix();
  74916. for (var i = 0; i < 10; ++i) {
  74917. m.data[i] = this.data[i] + matrix.data[i];
  74918. }
  74919. return m;
  74920. };
  74921. QuadraticMatrix.FromData = function (a, b, c, d) {
  74922. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74923. };
  74924. //returning an array to avoid garbage collection
  74925. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74926. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74927. };
  74928. return QuadraticMatrix;
  74929. }());
  74930. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74931. var Reference = /** @class */ (function () {
  74932. function Reference(vertexId, triangleId) {
  74933. this.vertexId = vertexId;
  74934. this.triangleId = triangleId;
  74935. }
  74936. return Reference;
  74937. }());
  74938. BABYLON.Reference = Reference;
  74939. /**
  74940. * An implementation of the Quadratic Error simplification algorithm.
  74941. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74942. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74943. * @author RaananW
  74944. */
  74945. var QuadraticErrorSimplification = /** @class */ (function () {
  74946. function QuadraticErrorSimplification(_mesh) {
  74947. this._mesh = _mesh;
  74948. this.syncIterations = 5000;
  74949. this.aggressiveness = 7;
  74950. this.decimationIterations = 100;
  74951. this.boundingBoxEpsilon = BABYLON.Epsilon;
  74952. }
  74953. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  74954. var _this = this;
  74955. this.initDecimatedMesh();
  74956. //iterating through the submeshes array, one after the other.
  74957. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  74958. _this.initWithMesh(loop.index, function () {
  74959. _this.runDecimation(settings, loop.index, function () {
  74960. loop.executeNext();
  74961. });
  74962. }, settings.optimizeMesh);
  74963. }, function () {
  74964. setTimeout(function () {
  74965. successCallback(_this._reconstructedMesh);
  74966. }, 0);
  74967. });
  74968. };
  74969. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  74970. var _this = this;
  74971. var targetCount = ~~(this.triangles.length * settings.quality);
  74972. var deletedTriangles = 0;
  74973. var triangleCount = this.triangles.length;
  74974. var iterationFunction = function (iteration, callback) {
  74975. setTimeout(function () {
  74976. if (iteration % 5 === 0) {
  74977. _this.updateMesh(iteration === 0);
  74978. }
  74979. for (var i = 0; i < _this.triangles.length; ++i) {
  74980. _this.triangles[i].isDirty = false;
  74981. }
  74982. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  74983. var trianglesIterator = function (i) {
  74984. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  74985. var t = _this.triangles[tIdx];
  74986. if (!t)
  74987. return;
  74988. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  74989. return;
  74990. }
  74991. for (var j = 0; j < 3; ++j) {
  74992. if (t.error[j] < threshold) {
  74993. var deleted0 = [];
  74994. var deleted1 = [];
  74995. var v0 = t.vertices[j];
  74996. var v1 = t.vertices[(j + 1) % 3];
  74997. if (v0.isBorder || v1.isBorder)
  74998. continue;
  74999. var p = BABYLON.Vector3.Zero();
  75000. var n = BABYLON.Vector3.Zero();
  75001. var uv = BABYLON.Vector2.Zero();
  75002. var color = new BABYLON.Color4(0, 0, 0, 1);
  75003. _this.calculateError(v0, v1, p, n, uv, color);
  75004. var delTr = new Array();
  75005. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75006. continue;
  75007. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75008. continue;
  75009. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75010. continue;
  75011. var uniqueArray = new Array();
  75012. delTr.forEach(function (deletedT) {
  75013. if (uniqueArray.indexOf(deletedT) === -1) {
  75014. deletedT.deletePending = true;
  75015. uniqueArray.push(deletedT);
  75016. }
  75017. });
  75018. if (uniqueArray.length % 2 !== 0) {
  75019. continue;
  75020. }
  75021. v0.q = v1.q.add(v0.q);
  75022. v0.updatePosition(p);
  75023. var tStart = _this.references.length;
  75024. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75025. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75026. var tCount = _this.references.length - tStart;
  75027. if (tCount <= v0.triangleCount) {
  75028. if (tCount) {
  75029. for (var c = 0; c < tCount; c++) {
  75030. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75031. }
  75032. }
  75033. }
  75034. else {
  75035. v0.triangleStart = tStart;
  75036. }
  75037. v0.triangleCount = tCount;
  75038. break;
  75039. }
  75040. }
  75041. };
  75042. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75043. }, 0);
  75044. };
  75045. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75046. if (triangleCount - deletedTriangles <= targetCount)
  75047. loop.breakLoop();
  75048. else {
  75049. iterationFunction(loop.index, function () {
  75050. loop.executeNext();
  75051. });
  75052. }
  75053. }, function () {
  75054. setTimeout(function () {
  75055. //reconstruct this part of the mesh
  75056. _this.reconstructMesh(submeshIndex);
  75057. successCallback();
  75058. }, 0);
  75059. });
  75060. };
  75061. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75062. var _this = this;
  75063. this.vertices = [];
  75064. this.triangles = [];
  75065. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75066. var indices = this._mesh.getIndices();
  75067. var submesh = this._mesh.subMeshes[submeshIndex];
  75068. var findInVertices = function (positionToSearch) {
  75069. if (optimizeMesh) {
  75070. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75071. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75072. return _this.vertices[ii];
  75073. }
  75074. }
  75075. }
  75076. return null;
  75077. };
  75078. var vertexReferences = [];
  75079. var vertexInit = function (i) {
  75080. if (!positionData) {
  75081. return;
  75082. }
  75083. var offset = i + submesh.verticesStart;
  75084. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75085. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75086. vertex.originalOffsets.push(offset);
  75087. if (vertex.id === _this.vertices.length) {
  75088. _this.vertices.push(vertex);
  75089. }
  75090. vertexReferences.push(vertex.id);
  75091. };
  75092. //var totalVertices = mesh.getTotalVertices();
  75093. var totalVertices = submesh.verticesCount;
  75094. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75095. var indicesInit = function (i) {
  75096. if (!indices) {
  75097. return;
  75098. }
  75099. var offset = (submesh.indexStart / 3) + i;
  75100. var pos = (offset * 3);
  75101. var i0 = indices[pos + 0];
  75102. var i1 = indices[pos + 1];
  75103. var i2 = indices[pos + 2];
  75104. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75105. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75106. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75107. var triangle = new DecimationTriangle([v0, v1, v2]);
  75108. triangle.originalOffset = pos;
  75109. _this.triangles.push(triangle);
  75110. };
  75111. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75112. _this.init(callback);
  75113. });
  75114. });
  75115. };
  75116. QuadraticErrorSimplification.prototype.init = function (callback) {
  75117. var _this = this;
  75118. var triangleInit1 = function (i) {
  75119. var t = _this.triangles[i];
  75120. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75121. for (var j = 0; j < 3; j++) {
  75122. 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))));
  75123. }
  75124. };
  75125. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75126. var triangleInit2 = function (i) {
  75127. var t = _this.triangles[i];
  75128. for (var j = 0; j < 3; ++j) {
  75129. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75130. }
  75131. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75132. };
  75133. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75134. callback();
  75135. });
  75136. });
  75137. };
  75138. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75139. var newTriangles = [];
  75140. var i;
  75141. for (i = 0; i < this.vertices.length; ++i) {
  75142. this.vertices[i].triangleCount = 0;
  75143. }
  75144. var t;
  75145. var j;
  75146. for (i = 0; i < this.triangles.length; ++i) {
  75147. if (!this.triangles[i].deleted) {
  75148. t = this.triangles[i];
  75149. for (j = 0; j < 3; ++j) {
  75150. t.vertices[j].triangleCount = 1;
  75151. }
  75152. newTriangles.push(t);
  75153. }
  75154. }
  75155. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75156. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75157. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75158. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75159. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75160. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75161. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75162. var vertexCount = 0;
  75163. for (i = 0; i < this.vertices.length; ++i) {
  75164. var vertex = this.vertices[i];
  75165. vertex.id = vertexCount;
  75166. if (vertex.triangleCount) {
  75167. vertex.originalOffsets.forEach(function (originalOffset) {
  75168. if (!normalData) {
  75169. return;
  75170. }
  75171. newPositionData.push(vertex.position.x);
  75172. newPositionData.push(vertex.position.y);
  75173. newPositionData.push(vertex.position.z);
  75174. newNormalData.push(normalData[originalOffset * 3]);
  75175. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75176. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75177. if (uvs && uvs.length) {
  75178. newUVsData.push(uvs[(originalOffset * 2)]);
  75179. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75180. }
  75181. else if (colorsData && colorsData.length) {
  75182. newColorsData.push(colorsData[(originalOffset * 4)]);
  75183. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75184. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75185. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75186. }
  75187. ++vertexCount;
  75188. });
  75189. }
  75190. }
  75191. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75192. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75193. var submeshesArray = this._reconstructedMesh.subMeshes;
  75194. this._reconstructedMesh.subMeshes = [];
  75195. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75196. var originalIndices = this._mesh.getIndices();
  75197. for (i = 0; i < newTriangles.length; ++i) {
  75198. t = newTriangles[i]; //now get the new referencing point for each vertex
  75199. [0, 1, 2].forEach(function (idx) {
  75200. var id = originalIndices[t.originalOffset + idx];
  75201. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75202. if (offset < 0)
  75203. offset = 0;
  75204. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75205. });
  75206. }
  75207. //overwriting the old vertex buffers and indices.
  75208. this._reconstructedMesh.setIndices(newIndicesArray);
  75209. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75210. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75211. if (newUVsData.length > 0)
  75212. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75213. if (newColorsData.length > 0)
  75214. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75215. //create submesh
  75216. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75217. if (submeshIndex > 0) {
  75218. this._reconstructedMesh.subMeshes = [];
  75219. submeshesArray.forEach(function (submesh) {
  75220. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75221. });
  75222. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75223. }
  75224. };
  75225. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75226. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75227. this._reconstructedMesh.material = this._mesh.material;
  75228. this._reconstructedMesh.parent = this._mesh.parent;
  75229. this._reconstructedMesh.isVisible = false;
  75230. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75231. };
  75232. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75233. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75234. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75235. if (t.deleted)
  75236. continue;
  75237. var s = this.references[vertex1.triangleStart + i].vertexId;
  75238. var v1 = t.vertices[(s + 1) % 3];
  75239. var v2 = t.vertices[(s + 2) % 3];
  75240. if ((v1 === vertex2 || v2 === vertex2)) {
  75241. deletedArray[i] = true;
  75242. delTr.push(t);
  75243. continue;
  75244. }
  75245. var d1 = v1.position.subtract(point);
  75246. d1 = d1.normalize();
  75247. var d2 = v2.position.subtract(point);
  75248. d2 = d2.normalize();
  75249. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75250. return true;
  75251. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75252. deletedArray[i] = false;
  75253. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75254. return true;
  75255. }
  75256. return false;
  75257. };
  75258. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75259. var newDeleted = deletedTriangles;
  75260. for (var i = 0; i < vertex.triangleCount; ++i) {
  75261. var ref = this.references[vertex.triangleStart + i];
  75262. var t = this.triangles[ref.triangleId];
  75263. if (t.deleted)
  75264. continue;
  75265. if (deletedArray[i] && t.deletePending) {
  75266. t.deleted = true;
  75267. newDeleted++;
  75268. continue;
  75269. }
  75270. t.vertices[ref.vertexId] = origVertex;
  75271. t.isDirty = true;
  75272. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75273. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75274. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75275. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75276. this.references.push(ref);
  75277. }
  75278. return newDeleted;
  75279. };
  75280. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75281. for (var i = 0; i < this.vertices.length; ++i) {
  75282. var vCount = [];
  75283. var vId = [];
  75284. var v = this.vertices[i];
  75285. var j;
  75286. for (j = 0; j < v.triangleCount; ++j) {
  75287. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75288. for (var ii = 0; ii < 3; ii++) {
  75289. var ofs = 0;
  75290. var vv = triangle.vertices[ii];
  75291. while (ofs < vCount.length) {
  75292. if (vId[ofs] === vv.id)
  75293. break;
  75294. ++ofs;
  75295. }
  75296. if (ofs === vCount.length) {
  75297. vCount.push(1);
  75298. vId.push(vv.id);
  75299. }
  75300. else {
  75301. vCount[ofs]++;
  75302. }
  75303. }
  75304. }
  75305. for (j = 0; j < vCount.length; ++j) {
  75306. if (vCount[j] === 1) {
  75307. this.vertices[vId[j]].isBorder = true;
  75308. }
  75309. else {
  75310. this.vertices[vId[j]].isBorder = false;
  75311. }
  75312. }
  75313. }
  75314. };
  75315. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75316. if (identifyBorders === void 0) { identifyBorders = false; }
  75317. var i;
  75318. if (!identifyBorders) {
  75319. var newTrianglesVector = [];
  75320. for (i = 0; i < this.triangles.length; ++i) {
  75321. if (!this.triangles[i].deleted) {
  75322. newTrianglesVector.push(this.triangles[i]);
  75323. }
  75324. }
  75325. this.triangles = newTrianglesVector;
  75326. }
  75327. for (i = 0; i < this.vertices.length; ++i) {
  75328. this.vertices[i].triangleCount = 0;
  75329. this.vertices[i].triangleStart = 0;
  75330. }
  75331. var t;
  75332. var j;
  75333. var v;
  75334. for (i = 0; i < this.triangles.length; ++i) {
  75335. t = this.triangles[i];
  75336. for (j = 0; j < 3; ++j) {
  75337. v = t.vertices[j];
  75338. v.triangleCount++;
  75339. }
  75340. }
  75341. var tStart = 0;
  75342. for (i = 0; i < this.vertices.length; ++i) {
  75343. this.vertices[i].triangleStart = tStart;
  75344. tStart += this.vertices[i].triangleCount;
  75345. this.vertices[i].triangleCount = 0;
  75346. }
  75347. var newReferences = new Array(this.triangles.length * 3);
  75348. for (i = 0; i < this.triangles.length; ++i) {
  75349. t = this.triangles[i];
  75350. for (j = 0; j < 3; ++j) {
  75351. v = t.vertices[j];
  75352. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75353. v.triangleCount++;
  75354. }
  75355. }
  75356. this.references = newReferences;
  75357. if (identifyBorders) {
  75358. this.identifyBorder();
  75359. }
  75360. };
  75361. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75362. var x = point.x;
  75363. var y = point.y;
  75364. var z = point.z;
  75365. 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
  75366. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75367. };
  75368. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75369. var q = vertex1.q.add(vertex2.q);
  75370. var border = vertex1.isBorder && vertex2.isBorder;
  75371. var error = 0;
  75372. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75373. if (qDet !== 0 && !border) {
  75374. if (!pointResult) {
  75375. pointResult = BABYLON.Vector3.Zero();
  75376. }
  75377. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75378. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75379. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75380. error = this.vertexError(q, pointResult);
  75381. }
  75382. else {
  75383. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75384. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75385. var error1 = this.vertexError(q, vertex1.position);
  75386. var error2 = this.vertexError(q, vertex2.position);
  75387. var error3 = this.vertexError(q, p3);
  75388. error = Math.min(error1, error2, error3);
  75389. if (error === error1) {
  75390. if (pointResult) {
  75391. pointResult.copyFrom(vertex1.position);
  75392. }
  75393. }
  75394. else if (error === error2) {
  75395. if (pointResult) {
  75396. pointResult.copyFrom(vertex2.position);
  75397. }
  75398. }
  75399. else {
  75400. if (pointResult) {
  75401. pointResult.copyFrom(p3);
  75402. }
  75403. }
  75404. }
  75405. return error;
  75406. };
  75407. return QuadraticErrorSimplification;
  75408. }());
  75409. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75410. })(BABYLON || (BABYLON = {}));
  75411. //# sourceMappingURL=babylon.meshSimplification.js.map
  75412. var BABYLON;
  75413. (function (BABYLON) {
  75414. var MeshLODLevel = /** @class */ (function () {
  75415. function MeshLODLevel(distance, mesh) {
  75416. this.distance = distance;
  75417. this.mesh = mesh;
  75418. }
  75419. return MeshLODLevel;
  75420. }());
  75421. BABYLON.MeshLODLevel = MeshLODLevel;
  75422. })(BABYLON || (BABYLON = {}));
  75423. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75424. var BABYLON;
  75425. (function (BABYLON) {
  75426. /**
  75427. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75428. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75429. */
  75430. var SceneOptimization = /** @class */ (function () {
  75431. /**
  75432. * Creates the SceneOptimization object
  75433. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75434. * @param desc defines the description associated with the optimization
  75435. */
  75436. function SceneOptimization(priority) {
  75437. if (priority === void 0) { priority = 0; }
  75438. this.priority = priority;
  75439. }
  75440. /**
  75441. * Gets a string describing the action executed by the current optimization
  75442. */
  75443. SceneOptimization.prototype.getDescription = function () {
  75444. return "";
  75445. };
  75446. /**
  75447. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75448. * @param scene defines the current scene where to apply this optimization
  75449. * @returnstrue if everything that can be done was applied
  75450. */
  75451. SceneOptimization.prototype.apply = function (scene) {
  75452. return true;
  75453. };
  75454. ;
  75455. return SceneOptimization;
  75456. }());
  75457. BABYLON.SceneOptimization = SceneOptimization;
  75458. /**
  75459. * Defines an optimization used to reduce the size of render target textures
  75460. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75461. */
  75462. var TextureOptimization = /** @class */ (function (_super) {
  75463. __extends(TextureOptimization, _super);
  75464. /**
  75465. * Creates the TextureOptimization object
  75466. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75467. * @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
  75468. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75469. */
  75470. function TextureOptimization(priority, maximumSize, step) {
  75471. if (priority === void 0) { priority = 0; }
  75472. if (maximumSize === void 0) { maximumSize = 1024; }
  75473. if (step === void 0) { step = 0.5; }
  75474. var _this = _super.call(this, priority) || this;
  75475. _this.priority = priority;
  75476. _this.maximumSize = maximumSize;
  75477. _this.step = step;
  75478. return _this;
  75479. }
  75480. /**
  75481. * Gets a string describing the action executed by the current optimization
  75482. */
  75483. TextureOptimization.prototype.getDescription = function () {
  75484. return "Reducing render target texture size to " + this.maximumSize;
  75485. };
  75486. /**
  75487. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75488. * @param scene defines the current scene where to apply this optimization
  75489. */
  75490. TextureOptimization.prototype.apply = function (scene) {
  75491. var allDone = true;
  75492. for (var index = 0; index < scene.textures.length; index++) {
  75493. var texture = scene.textures[index];
  75494. if (!texture.canRescale || texture.getContext) {
  75495. continue;
  75496. }
  75497. var currentSize = texture.getSize();
  75498. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75499. if (maxDimension > this.maximumSize) {
  75500. texture.scale(this.step);
  75501. allDone = false;
  75502. }
  75503. }
  75504. return allDone;
  75505. };
  75506. return TextureOptimization;
  75507. }(SceneOptimization));
  75508. BABYLON.TextureOptimization = TextureOptimization;
  75509. /**
  75510. * Defines an optimization used to increase or decrease the rendering resolution
  75511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75512. */
  75513. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75514. __extends(HardwareScalingOptimization, _super);
  75515. /**
  75516. * Creates the HardwareScalingOptimization object
  75517. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75518. * @param maximumScale
  75519. * @param step
  75520. */
  75521. function HardwareScalingOptimization(priority, maximumScale, step) {
  75522. if (priority === void 0) { priority = 0; }
  75523. if (maximumScale === void 0) { maximumScale = 2; }
  75524. if (step === void 0) { step = 0.25; }
  75525. var _this = _super.call(this, priority) || this;
  75526. _this.priority = priority;
  75527. _this.maximumScale = maximumScale;
  75528. _this.step = step;
  75529. _this._currentScale = -1;
  75530. _this._directionOffset = 1;
  75531. return _this;
  75532. }
  75533. /**
  75534. * Gets a string describing the action executed by the current optimization
  75535. */
  75536. HardwareScalingOptimization.prototype.getDescription = function () {
  75537. return "Setting hardware scaling level to " + this._currentScale;
  75538. };
  75539. /**
  75540. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75541. * @param scene defines the current scene where to apply this optimization
  75542. */
  75543. HardwareScalingOptimization.prototype.apply = function (scene) {
  75544. if (this._currentScale === -1) {
  75545. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75546. if (this._currentScale > this.maximumScale) {
  75547. this._directionOffset = -1;
  75548. }
  75549. }
  75550. this._currentScale += this._directionOffset * this.step;
  75551. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75552. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75553. };
  75554. ;
  75555. return HardwareScalingOptimization;
  75556. }(SceneOptimization));
  75557. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75558. /**
  75559. * Defines an optimization used to remove shadows
  75560. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75561. */
  75562. var ShadowsOptimization = /** @class */ (function (_super) {
  75563. __extends(ShadowsOptimization, _super);
  75564. function ShadowsOptimization() {
  75565. return _super !== null && _super.apply(this, arguments) || this;
  75566. }
  75567. /**
  75568. * Gets a string describing the action executed by the current optimization
  75569. */
  75570. ShadowsOptimization.prototype.getDescription = function () {
  75571. return "Turning shadows off";
  75572. };
  75573. /**
  75574. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75575. * @param scene defines the current scene where to apply this optimization
  75576. */
  75577. ShadowsOptimization.prototype.apply = function (scene) {
  75578. scene.shadowsEnabled = false;
  75579. return true;
  75580. };
  75581. ;
  75582. return ShadowsOptimization;
  75583. }(SceneOptimization));
  75584. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75585. /**
  75586. * Defines an optimization used to turn post-processes off
  75587. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75588. */
  75589. var PostProcessesOptimization = /** @class */ (function (_super) {
  75590. __extends(PostProcessesOptimization, _super);
  75591. function PostProcessesOptimization() {
  75592. return _super !== null && _super.apply(this, arguments) || this;
  75593. }
  75594. /**
  75595. * Gets a string describing the action executed by the current optimization
  75596. */
  75597. PostProcessesOptimization.prototype.getDescription = function () {
  75598. return "Turning post-processes off";
  75599. };
  75600. /**
  75601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75602. * @param scene defines the current scene where to apply this optimization
  75603. */
  75604. PostProcessesOptimization.prototype.apply = function (scene) {
  75605. scene.postProcessesEnabled = false;
  75606. return true;
  75607. };
  75608. ;
  75609. return PostProcessesOptimization;
  75610. }(SceneOptimization));
  75611. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75612. /**
  75613. * Defines an optimization used to turn lens flares off
  75614. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75615. */
  75616. var LensFlaresOptimization = /** @class */ (function (_super) {
  75617. __extends(LensFlaresOptimization, _super);
  75618. function LensFlaresOptimization() {
  75619. return _super !== null && _super.apply(this, arguments) || this;
  75620. }
  75621. /**
  75622. * Gets a string describing the action executed by the current optimization
  75623. */
  75624. LensFlaresOptimization.prototype.getDescription = function () {
  75625. return "Turning lens flares off";
  75626. };
  75627. /**
  75628. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75629. * @param scene defines the current scene where to apply this optimization
  75630. */
  75631. LensFlaresOptimization.prototype.apply = function (scene) {
  75632. scene.lensFlaresEnabled = false;
  75633. return true;
  75634. };
  75635. ;
  75636. return LensFlaresOptimization;
  75637. }(SceneOptimization));
  75638. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75639. /**
  75640. * Defines an optimization based on user defined callback.
  75641. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75642. */
  75643. var CustomOptimization = /** @class */ (function (_super) {
  75644. __extends(CustomOptimization, _super);
  75645. function CustomOptimization() {
  75646. return _super !== null && _super.apply(this, arguments) || this;
  75647. }
  75648. /**
  75649. * Gets a string describing the action executed by the current optimization
  75650. */
  75651. CustomOptimization.prototype.getDescription = function () {
  75652. if (this.onGetDescription) {
  75653. return this.onGetDescription();
  75654. }
  75655. return "Running user defined callback";
  75656. };
  75657. /**
  75658. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75659. * @param scene defines the current scene where to apply this optimization
  75660. */
  75661. CustomOptimization.prototype.apply = function (scene) {
  75662. if (this.onApply) {
  75663. return this.onApply(scene);
  75664. }
  75665. return true;
  75666. };
  75667. ;
  75668. return CustomOptimization;
  75669. }(SceneOptimization));
  75670. BABYLON.CustomOptimization = CustomOptimization;
  75671. /**
  75672. * Defines an optimization used to turn particles off
  75673. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75674. */
  75675. var ParticlesOptimization = /** @class */ (function (_super) {
  75676. __extends(ParticlesOptimization, _super);
  75677. function ParticlesOptimization() {
  75678. return _super !== null && _super.apply(this, arguments) || this;
  75679. }
  75680. /**
  75681. * Gets a string describing the action executed by the current optimization
  75682. */
  75683. ParticlesOptimization.prototype.getDescription = function () {
  75684. return "Turning particles off";
  75685. };
  75686. /**
  75687. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75688. * @param scene defines the current scene where to apply this optimization
  75689. */
  75690. ParticlesOptimization.prototype.apply = function (scene) {
  75691. scene.particlesEnabled = false;
  75692. return true;
  75693. };
  75694. ;
  75695. return ParticlesOptimization;
  75696. }(SceneOptimization));
  75697. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75698. /**
  75699. * Defines an optimization used to turn render targets off
  75700. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75701. */
  75702. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75703. __extends(RenderTargetsOptimization, _super);
  75704. function RenderTargetsOptimization() {
  75705. return _super !== null && _super.apply(this, arguments) || this;
  75706. }
  75707. /**
  75708. * Gets a string describing the action executed by the current optimization
  75709. */
  75710. RenderTargetsOptimization.prototype.getDescription = function () {
  75711. return "Turning render targets off";
  75712. };
  75713. /**
  75714. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75715. * @param scene defines the current scene where to apply this optimization
  75716. */
  75717. RenderTargetsOptimization.prototype.apply = function (scene) {
  75718. scene.renderTargetsEnabled = false;
  75719. return true;
  75720. };
  75721. ;
  75722. return RenderTargetsOptimization;
  75723. }(SceneOptimization));
  75724. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75725. /**
  75726. * Defines an optimization used to merge meshes with compatible materials
  75727. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75728. */
  75729. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75730. __extends(MergeMeshesOptimization, _super);
  75731. function MergeMeshesOptimization() {
  75732. var _this = _super !== null && _super.apply(this, arguments) || this;
  75733. _this._canBeMerged = function (abstractMesh) {
  75734. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75735. return false;
  75736. }
  75737. var mesh = abstractMesh;
  75738. if (!mesh.isVisible || !mesh.isEnabled()) {
  75739. return false;
  75740. }
  75741. if (mesh.instances.length > 0) {
  75742. return false;
  75743. }
  75744. if (mesh.skeleton || mesh.hasLODLevels) {
  75745. return false;
  75746. }
  75747. if (mesh.parent) {
  75748. return false;
  75749. }
  75750. return true;
  75751. };
  75752. return _this;
  75753. }
  75754. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75755. /**
  75756. * Gets or sets a boolean which defines if optimization octree has to be updated
  75757. */
  75758. get: function () {
  75759. return MergeMeshesOptimization._UpdateSelectionTree;
  75760. },
  75761. /**
  75762. * Gets or sets a boolean which defines if optimization octree has to be updated
  75763. */
  75764. set: function (value) {
  75765. MergeMeshesOptimization._UpdateSelectionTree = value;
  75766. },
  75767. enumerable: true,
  75768. configurable: true
  75769. });
  75770. /**
  75771. * Gets a string describing the action executed by the current optimization
  75772. */
  75773. MergeMeshesOptimization.prototype.getDescription = function () {
  75774. return "Merging similar meshes together";
  75775. };
  75776. /**
  75777. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75778. * @param scene defines the current scene where to apply this optimization
  75779. */
  75780. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  75781. var globalPool = scene.meshes.slice(0);
  75782. var globalLength = globalPool.length;
  75783. for (var index = 0; index < globalLength; index++) {
  75784. var currentPool = new Array();
  75785. var current = globalPool[index];
  75786. // Checks
  75787. if (!this._canBeMerged(current)) {
  75788. continue;
  75789. }
  75790. currentPool.push(current);
  75791. // Find compatible meshes
  75792. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75793. var otherMesh = globalPool[subIndex];
  75794. if (!this._canBeMerged(otherMesh)) {
  75795. continue;
  75796. }
  75797. if (otherMesh.material !== current.material) {
  75798. continue;
  75799. }
  75800. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75801. continue;
  75802. }
  75803. currentPool.push(otherMesh);
  75804. globalLength--;
  75805. globalPool.splice(subIndex, 1);
  75806. subIndex--;
  75807. }
  75808. if (currentPool.length < 2) {
  75809. continue;
  75810. }
  75811. // Merge meshes
  75812. BABYLON.Mesh.MergeMeshes(currentPool);
  75813. }
  75814. if (updateSelectionTree != undefined) {
  75815. if (updateSelectionTree) {
  75816. scene.createOrUpdateSelectionOctree();
  75817. }
  75818. }
  75819. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75820. scene.createOrUpdateSelectionOctree();
  75821. }
  75822. return true;
  75823. };
  75824. ;
  75825. MergeMeshesOptimization._UpdateSelectionTree = false;
  75826. return MergeMeshesOptimization;
  75827. }(SceneOptimization));
  75828. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75829. /**
  75830. * Defines a list of options used by SceneOptimizer
  75831. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75832. */
  75833. var SceneOptimizerOptions = /** @class */ (function () {
  75834. /**
  75835. * Creates a new list of options used by SceneOptimizer
  75836. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  75837. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  75838. */
  75839. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75840. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75841. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75842. this.targetFrameRate = targetFrameRate;
  75843. this.trackerDuration = trackerDuration;
  75844. /**
  75845. * Gets the list of optimizations to apply
  75846. */
  75847. this.optimizations = new Array();
  75848. }
  75849. /**
  75850. * Add a new optimization
  75851. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  75852. */
  75853. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  75854. this.optimizations.push(optimization);
  75855. return this;
  75856. };
  75857. /**
  75858. * Add a new custom optimization
  75859. * @param onApply defines the callback called to apply the custom optimization.
  75860. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  75861. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75862. */
  75863. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  75864. if (priority === void 0) { priority = 0; }
  75865. var optimization = new CustomOptimization(priority);
  75866. optimization.onApply = onApply;
  75867. optimization.onGetDescription = onGetDescription;
  75868. this.optimizations.push(optimization);
  75869. return this;
  75870. };
  75871. /**
  75872. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  75873. * @param targetFrameRate defines the target frame rate (60 by default)
  75874. * @returns a SceneOptimizerOptions object
  75875. */
  75876. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75877. var result = new SceneOptimizerOptions(targetFrameRate);
  75878. var priority = 0;
  75879. result.addOptimization(new MergeMeshesOptimization(priority));
  75880. result.addOptimization(new ShadowsOptimization(priority));
  75881. result.addOptimization(new LensFlaresOptimization(priority));
  75882. // Next priority
  75883. priority++;
  75884. result.addOptimization(new PostProcessesOptimization(priority));
  75885. result.addOptimization(new ParticlesOptimization(priority));
  75886. // Next priority
  75887. priority++;
  75888. result.addOptimization(new TextureOptimization(priority, 1024));
  75889. return result;
  75890. };
  75891. /**
  75892. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  75893. * @param targetFrameRate defines the target frame rate (60 by default)
  75894. * @returns a SceneOptimizerOptions object
  75895. */
  75896. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75897. var result = new SceneOptimizerOptions(targetFrameRate);
  75898. var priority = 0;
  75899. result.addOptimization(new MergeMeshesOptimization(priority));
  75900. result.addOptimization(new ShadowsOptimization(priority));
  75901. result.addOptimization(new LensFlaresOptimization(priority));
  75902. // Next priority
  75903. priority++;
  75904. result.addOptimization(new PostProcessesOptimization(priority));
  75905. result.addOptimization(new ParticlesOptimization(priority));
  75906. // Next priority
  75907. priority++;
  75908. result.addOptimization(new TextureOptimization(priority, 512));
  75909. // Next priority
  75910. priority++;
  75911. result.addOptimization(new RenderTargetsOptimization(priority));
  75912. // Next priority
  75913. priority++;
  75914. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  75915. return result;
  75916. };
  75917. /**
  75918. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  75919. * @param targetFrameRate defines the target frame rate (60 by default)
  75920. * @returns a SceneOptimizerOptions object
  75921. */
  75922. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  75923. var result = new SceneOptimizerOptions(targetFrameRate);
  75924. var priority = 0;
  75925. result.addOptimization(new MergeMeshesOptimization(priority));
  75926. result.addOptimization(new ShadowsOptimization(priority));
  75927. result.addOptimization(new LensFlaresOptimization(priority));
  75928. // Next priority
  75929. priority++;
  75930. result.addOptimization(new PostProcessesOptimization(priority));
  75931. result.addOptimization(new ParticlesOptimization(priority));
  75932. // Next priority
  75933. priority++;
  75934. result.addOptimization(new TextureOptimization(priority, 256));
  75935. // Next priority
  75936. priority++;
  75937. result.addOptimization(new RenderTargetsOptimization(priority));
  75938. // Next priority
  75939. priority++;
  75940. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  75941. return result;
  75942. };
  75943. return SceneOptimizerOptions;
  75944. }());
  75945. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  75946. /**
  75947. * Class used to run optimizations in order to reach a target frame rate
  75948. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75949. */
  75950. var SceneOptimizer = /** @class */ (function () {
  75951. /**
  75952. * Creates a new SceneOptimizer
  75953. * @param scene defines the scene to work on
  75954. * @param options defines the options to use with the SceneOptimizer
  75955. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  75956. */
  75957. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  75958. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  75959. this._isRunning = false;
  75960. this._currentPriorityLevel = 0;
  75961. this._targetFrameRate = 60;
  75962. this._trackerDuration = 2000;
  75963. this._currentFrameRate = 0;
  75964. /**
  75965. * Defines an observable called when the optimizer reaches the target frame rate
  75966. */
  75967. this.onSuccessObservable = new BABYLON.Observable();
  75968. /**
  75969. * Defines an observable called when the optimizer enables an optimization
  75970. */
  75971. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  75972. /**
  75973. * Defines an observable called when the optimizer is not able to reach the target frame rate
  75974. */
  75975. this.onFailureObservable = new BABYLON.Observable();
  75976. if (!options) {
  75977. this._options = new SceneOptimizerOptions();
  75978. }
  75979. else {
  75980. this._options = options;
  75981. }
  75982. if (this._options.targetFrameRate) {
  75983. this._targetFrameRate = this._options.targetFrameRate;
  75984. }
  75985. if (this._options.trackerDuration) {
  75986. this._trackerDuration = this._options.trackerDuration;
  75987. }
  75988. if (autoGeneratePriorities) {
  75989. var priority = 0;
  75990. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  75991. var optim = _a[_i];
  75992. optim.priority = priority++;
  75993. }
  75994. }
  75995. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75996. }
  75997. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  75998. /**
  75999. * Gets the current priority level (0 at start)
  76000. */
  76001. get: function () {
  76002. return this._currentPriorityLevel;
  76003. },
  76004. enumerable: true,
  76005. configurable: true
  76006. });
  76007. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76008. /**
  76009. * Gets the current frame rate checked by the SceneOptimizer
  76010. */
  76011. get: function () {
  76012. return this._currentFrameRate;
  76013. },
  76014. enumerable: true,
  76015. configurable: true
  76016. });
  76017. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76018. /**
  76019. * Gets or sets the current target frame rate (60 by default)
  76020. */
  76021. get: function () {
  76022. return this._targetFrameRate;
  76023. },
  76024. /**
  76025. * Gets or sets the current target frame rate (60 by default)
  76026. */
  76027. set: function (value) {
  76028. this._targetFrameRate = value;
  76029. },
  76030. enumerable: true,
  76031. configurable: true
  76032. });
  76033. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76034. /**
  76035. * Gets or sets the current interval between two checks (every 2000ms by default)
  76036. */
  76037. get: function () {
  76038. return this._trackerDuration;
  76039. },
  76040. /**
  76041. * Gets or sets the current interval between two checks (every 2000ms by default)
  76042. */
  76043. set: function (value) {
  76044. this._trackerDuration = value;
  76045. },
  76046. enumerable: true,
  76047. configurable: true
  76048. });
  76049. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76050. /**
  76051. * Gets the list of active optimizations
  76052. */
  76053. get: function () {
  76054. return this._options.optimizations;
  76055. },
  76056. enumerable: true,
  76057. configurable: true
  76058. });
  76059. /**
  76060. * Stops the current optimizer
  76061. */
  76062. SceneOptimizer.prototype.stop = function () {
  76063. this._isRunning = false;
  76064. };
  76065. SceneOptimizer.prototype.reset = function () {
  76066. this._currentPriorityLevel = 0;
  76067. };
  76068. SceneOptimizer.prototype.start = function () {
  76069. var _this = this;
  76070. if (this._isRunning) {
  76071. return;
  76072. }
  76073. this._isRunning = true;
  76074. // Let's wait for the scene to be ready before running our check
  76075. this._scene.executeWhenReady(function () {
  76076. setTimeout(function () {
  76077. _this._checkCurrentState();
  76078. }, _this._trackerDuration);
  76079. });
  76080. };
  76081. SceneOptimizer.prototype._checkCurrentState = function () {
  76082. var _this = this;
  76083. if (!this._isRunning) {
  76084. return;
  76085. }
  76086. var scene = this._scene;
  76087. var options = this._options;
  76088. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76089. if (this._currentFrameRate >= this._targetFrameRate) {
  76090. this._isRunning = false;
  76091. this.onSuccessObservable.notifyObservers(this);
  76092. return;
  76093. }
  76094. // Apply current level of optimizations
  76095. var allDone = true;
  76096. var noOptimizationApplied = true;
  76097. for (var index = 0; index < options.optimizations.length; index++) {
  76098. var optimization = options.optimizations[index];
  76099. if (optimization.priority === this._currentPriorityLevel) {
  76100. noOptimizationApplied = false;
  76101. allDone = allDone && optimization.apply(scene);
  76102. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76103. }
  76104. }
  76105. // If no optimization was applied, this is a failure :(
  76106. if (noOptimizationApplied) {
  76107. this._isRunning = false;
  76108. this.onFailureObservable.notifyObservers(this);
  76109. return;
  76110. }
  76111. // If all optimizations were done, move to next level
  76112. if (allDone) {
  76113. this._currentPriorityLevel++;
  76114. }
  76115. // Let's the system running for a specific amount of time before checking FPS
  76116. scene.executeWhenReady(function () {
  76117. setTimeout(function () {
  76118. _this._checkCurrentState();
  76119. }, _this._trackerDuration);
  76120. });
  76121. };
  76122. /**
  76123. * Release all resources
  76124. */
  76125. SceneOptimizer.prototype.dispose = function () {
  76126. this.onSuccessObservable.clear();
  76127. this.onFailureObservable.clear();
  76128. this.onNewOptimizationAppliedObservable.clear();
  76129. };
  76130. /**
  76131. * Helper function to create a SceneOptimizer with one single line of code
  76132. * @param scene defines the scene to work on
  76133. * @param options defines the options to use with the SceneOptimizer
  76134. * @param onSuccess defines a callback to call on success
  76135. * @param onFailure defines a callback to call on failure
  76136. */
  76137. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76138. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76139. if (onSuccess) {
  76140. optimizer.onSuccessObservable.add(function () {
  76141. onSuccess();
  76142. });
  76143. }
  76144. if (onFailure) {
  76145. optimizer.onFailureObservable.add(function () {
  76146. onFailure();
  76147. });
  76148. }
  76149. optimizer.start();
  76150. return optimizer;
  76151. };
  76152. return SceneOptimizer;
  76153. }());
  76154. BABYLON.SceneOptimizer = SceneOptimizer;
  76155. })(BABYLON || (BABYLON = {}));
  76156. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76157. var BABYLON;
  76158. (function (BABYLON) {
  76159. var OutlineRenderer = /** @class */ (function () {
  76160. function OutlineRenderer(scene) {
  76161. this.zOffset = 1;
  76162. this._scene = scene;
  76163. }
  76164. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76165. var _this = this;
  76166. if (useOverlay === void 0) { useOverlay = false; }
  76167. var scene = this._scene;
  76168. var engine = this._scene.getEngine();
  76169. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76170. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76171. return;
  76172. }
  76173. var mesh = subMesh.getRenderingMesh();
  76174. var material = subMesh.getMaterial();
  76175. if (!material || !scene.activeCamera) {
  76176. return;
  76177. }
  76178. engine.enableEffect(this._effect);
  76179. // Logarithmic depth
  76180. if (material.useLogarithmicDepth) {
  76181. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76182. }
  76183. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76184. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76185. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76186. // Bones
  76187. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76188. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76189. }
  76190. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76191. // Alpha test
  76192. if (material && material.needAlphaTesting()) {
  76193. var alphaTexture = material.getAlphaTestTexture();
  76194. if (alphaTexture) {
  76195. this._effect.setTexture("diffuseSampler", alphaTexture);
  76196. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76197. }
  76198. }
  76199. engine.setZOffset(-this.zOffset);
  76200. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76201. engine.setZOffset(0);
  76202. };
  76203. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76204. var defines = [];
  76205. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76206. var mesh = subMesh.getMesh();
  76207. var material = subMesh.getMaterial();
  76208. if (material) {
  76209. // Alpha test
  76210. if (material.needAlphaTesting()) {
  76211. defines.push("#define ALPHATEST");
  76212. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76213. attribs.push(BABYLON.VertexBuffer.UVKind);
  76214. defines.push("#define UV1");
  76215. }
  76216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76217. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76218. defines.push("#define UV2");
  76219. }
  76220. }
  76221. //Logarithmic depth
  76222. if (material.useLogarithmicDepth) {
  76223. defines.push("#define LOGARITHMICDEPTH");
  76224. }
  76225. }
  76226. // Bones
  76227. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76228. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76229. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76230. if (mesh.numBoneInfluencers > 4) {
  76231. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76232. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76233. }
  76234. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76235. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76236. }
  76237. else {
  76238. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76239. }
  76240. // Instances
  76241. if (useInstances) {
  76242. defines.push("#define INSTANCES");
  76243. attribs.push("world0");
  76244. attribs.push("world1");
  76245. attribs.push("world2");
  76246. attribs.push("world3");
  76247. }
  76248. // Get correct effect
  76249. var join = defines.join("\n");
  76250. if (this._cachedDefines !== join) {
  76251. this._cachedDefines = join;
  76252. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76253. }
  76254. return this._effect.isReady();
  76255. };
  76256. return OutlineRenderer;
  76257. }());
  76258. BABYLON.OutlineRenderer = OutlineRenderer;
  76259. })(BABYLON || (BABYLON = {}));
  76260. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76261. var BABYLON;
  76262. (function (BABYLON) {
  76263. var FaceAdjacencies = /** @class */ (function () {
  76264. function FaceAdjacencies() {
  76265. this.edges = new Array();
  76266. this.edgesConnectedCount = 0;
  76267. }
  76268. return FaceAdjacencies;
  76269. }());
  76270. var EdgesRenderer = /** @class */ (function () {
  76271. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76272. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76273. if (epsilon === void 0) { epsilon = 0.95; }
  76274. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76275. this.edgesWidthScalerForOrthographic = 1000.0;
  76276. this.edgesWidthScalerForPerspective = 50.0;
  76277. this._linesPositions = new Array();
  76278. this._linesNormals = new Array();
  76279. this._linesIndices = new Array();
  76280. this._buffers = {};
  76281. this._checkVerticesInsteadOfIndices = false;
  76282. this._source = source;
  76283. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76284. this._epsilon = epsilon;
  76285. this._prepareRessources();
  76286. this._generateEdgesLines();
  76287. }
  76288. EdgesRenderer.prototype._prepareRessources = function () {
  76289. if (this._lineShader) {
  76290. return;
  76291. }
  76292. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76293. attributes: ["position", "normal"],
  76294. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76295. });
  76296. this._lineShader.disableDepthWrite = true;
  76297. this._lineShader.backFaceCulling = false;
  76298. };
  76299. EdgesRenderer.prototype._rebuild = function () {
  76300. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76301. if (buffer) {
  76302. buffer._rebuild();
  76303. }
  76304. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76305. if (buffer) {
  76306. buffer._rebuild();
  76307. }
  76308. var scene = this._source.getScene();
  76309. var engine = scene.getEngine();
  76310. this._ib = engine.createIndexBuffer(this._linesIndices);
  76311. };
  76312. EdgesRenderer.prototype.dispose = function () {
  76313. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76314. if (buffer) {
  76315. buffer.dispose();
  76316. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76317. }
  76318. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76319. if (buffer) {
  76320. buffer.dispose();
  76321. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76322. }
  76323. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76324. this._lineShader.dispose();
  76325. };
  76326. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76327. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76328. return 0;
  76329. }
  76330. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76331. return 1;
  76332. }
  76333. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76334. return 2;
  76335. }
  76336. return -1;
  76337. };
  76338. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76339. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76340. return 0;
  76341. }
  76342. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76343. return 1;
  76344. }
  76345. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76346. return 2;
  76347. }
  76348. return -1;
  76349. };
  76350. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76351. var needToCreateLine;
  76352. if (edge === undefined) {
  76353. needToCreateLine = true;
  76354. }
  76355. else {
  76356. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76357. needToCreateLine = dotProduct < this._epsilon;
  76358. }
  76359. if (needToCreateLine) {
  76360. var offset = this._linesPositions.length / 3;
  76361. var normal = p0.subtract(p1);
  76362. normal.normalize();
  76363. // Positions
  76364. this._linesPositions.push(p0.x);
  76365. this._linesPositions.push(p0.y);
  76366. this._linesPositions.push(p0.z);
  76367. this._linesPositions.push(p0.x);
  76368. this._linesPositions.push(p0.y);
  76369. this._linesPositions.push(p0.z);
  76370. this._linesPositions.push(p1.x);
  76371. this._linesPositions.push(p1.y);
  76372. this._linesPositions.push(p1.z);
  76373. this._linesPositions.push(p1.x);
  76374. this._linesPositions.push(p1.y);
  76375. this._linesPositions.push(p1.z);
  76376. // Normals
  76377. this._linesNormals.push(p1.x);
  76378. this._linesNormals.push(p1.y);
  76379. this._linesNormals.push(p1.z);
  76380. this._linesNormals.push(-1);
  76381. this._linesNormals.push(p1.x);
  76382. this._linesNormals.push(p1.y);
  76383. this._linesNormals.push(p1.z);
  76384. this._linesNormals.push(1);
  76385. this._linesNormals.push(p0.x);
  76386. this._linesNormals.push(p0.y);
  76387. this._linesNormals.push(p0.z);
  76388. this._linesNormals.push(-1);
  76389. this._linesNormals.push(p0.x);
  76390. this._linesNormals.push(p0.y);
  76391. this._linesNormals.push(p0.z);
  76392. this._linesNormals.push(1);
  76393. // Indices
  76394. this._linesIndices.push(offset);
  76395. this._linesIndices.push(offset + 1);
  76396. this._linesIndices.push(offset + 2);
  76397. this._linesIndices.push(offset);
  76398. this._linesIndices.push(offset + 2);
  76399. this._linesIndices.push(offset + 3);
  76400. }
  76401. };
  76402. EdgesRenderer.prototype._generateEdgesLines = function () {
  76403. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76404. var indices = this._source.getIndices();
  76405. if (!indices || !positions) {
  76406. return;
  76407. }
  76408. // First let's find adjacencies
  76409. var adjacencies = new Array();
  76410. var faceNormals = new Array();
  76411. var index;
  76412. var faceAdjacencies;
  76413. // Prepare faces
  76414. for (index = 0; index < indices.length; index += 3) {
  76415. faceAdjacencies = new FaceAdjacencies();
  76416. var p0Index = indices[index];
  76417. var p1Index = indices[index + 1];
  76418. var p2Index = indices[index + 2];
  76419. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76420. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76421. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76422. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76423. faceNormal.normalize();
  76424. faceNormals.push(faceNormal);
  76425. adjacencies.push(faceAdjacencies);
  76426. }
  76427. // Scan
  76428. for (index = 0; index < adjacencies.length; index++) {
  76429. faceAdjacencies = adjacencies[index];
  76430. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76431. var otherFaceAdjacencies = adjacencies[otherIndex];
  76432. if (faceAdjacencies.edgesConnectedCount === 3) {
  76433. break;
  76434. }
  76435. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76436. continue;
  76437. }
  76438. var otherP0 = indices[otherIndex * 3];
  76439. var otherP1 = indices[otherIndex * 3 + 1];
  76440. var otherP2 = indices[otherIndex * 3 + 2];
  76441. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76442. var otherEdgeIndex = 0;
  76443. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76444. continue;
  76445. }
  76446. switch (edgeIndex) {
  76447. case 0:
  76448. if (this._checkVerticesInsteadOfIndices) {
  76449. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76450. }
  76451. else {
  76452. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76453. }
  76454. break;
  76455. case 1:
  76456. if (this._checkVerticesInsteadOfIndices) {
  76457. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76458. }
  76459. else {
  76460. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76461. }
  76462. break;
  76463. case 2:
  76464. if (this._checkVerticesInsteadOfIndices) {
  76465. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76466. }
  76467. else {
  76468. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76469. }
  76470. break;
  76471. }
  76472. if (otherEdgeIndex === -1) {
  76473. continue;
  76474. }
  76475. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76476. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76477. faceAdjacencies.edgesConnectedCount++;
  76478. otherFaceAdjacencies.edgesConnectedCount++;
  76479. if (faceAdjacencies.edgesConnectedCount === 3) {
  76480. break;
  76481. }
  76482. }
  76483. }
  76484. }
  76485. // Create lines
  76486. for (index = 0; index < adjacencies.length; index++) {
  76487. // 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
  76488. var current = adjacencies[index];
  76489. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76490. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76491. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76492. }
  76493. // Merge into a single mesh
  76494. var engine = this._source.getScene().getEngine();
  76495. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76496. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76497. this._ib = engine.createIndexBuffer(this._linesIndices);
  76498. this._indicesCount = this._linesIndices.length;
  76499. };
  76500. EdgesRenderer.prototype.render = function () {
  76501. var scene = this._source.getScene();
  76502. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76503. return;
  76504. }
  76505. var engine = scene.getEngine();
  76506. this._lineShader._preBind();
  76507. // VBOs
  76508. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76509. scene.resetCachedMaterial();
  76510. this._lineShader.setColor4("color", this._source.edgesColor);
  76511. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76512. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76513. }
  76514. else {
  76515. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76516. }
  76517. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76518. this._lineShader.bind(this._source.getWorldMatrix());
  76519. // Draw order
  76520. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76521. this._lineShader.unbind();
  76522. engine.setDepthWrite(true);
  76523. };
  76524. return EdgesRenderer;
  76525. }());
  76526. BABYLON.EdgesRenderer = EdgesRenderer;
  76527. })(BABYLON || (BABYLON = {}));
  76528. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76529. var BABYLON;
  76530. (function (BABYLON) {
  76531. /**
  76532. * Special Glow Blur post process only blurring the alpha channel
  76533. * It enforces keeping the most luminous color in the color channel.
  76534. */
  76535. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76536. __extends(GlowBlurPostProcess, _super);
  76537. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76539. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76540. _this.direction = direction;
  76541. _this.kernel = kernel;
  76542. _this.onApplyObservable.add(function (effect) {
  76543. effect.setFloat2("screenSize", _this.width, _this.height);
  76544. effect.setVector2("direction", _this.direction);
  76545. effect.setFloat("blurWidth", _this.kernel);
  76546. });
  76547. return _this;
  76548. }
  76549. return GlowBlurPostProcess;
  76550. }(BABYLON.PostProcess));
  76551. /**
  76552. * The highlight layer Helps adding a glow effect around a mesh.
  76553. *
  76554. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76555. * glowy meshes to your scene.
  76556. *
  76557. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76558. */
  76559. var HighlightLayer = /** @class */ (function () {
  76560. /**
  76561. * Instantiates a new highlight Layer and references it to the scene..
  76562. * @param name The name of the layer
  76563. * @param scene The scene to use the layer in
  76564. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76565. */
  76566. function HighlightLayer(name, scene, options) {
  76567. this.name = name;
  76568. this._vertexBuffers = {};
  76569. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76570. this._meshes = {};
  76571. this._maxSize = 0;
  76572. this._shouldRender = false;
  76573. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76574. this._excludedMeshes = {};
  76575. /**
  76576. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76577. */
  76578. this.innerGlow = true;
  76579. /**
  76580. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76581. */
  76582. this.outerGlow = true;
  76583. /**
  76584. * Specifies wether the highlight layer is enabled or not.
  76585. */
  76586. this.isEnabled = true;
  76587. /**
  76588. * An event triggered when the highlight layer has been disposed.
  76589. * @type {BABYLON.Observable}
  76590. */
  76591. this.onDisposeObservable = new BABYLON.Observable();
  76592. /**
  76593. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76594. * @type {BABYLON.Observable}
  76595. */
  76596. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76597. /**
  76598. * An event triggered when the highlight layer is being blurred.
  76599. * @type {BABYLON.Observable}
  76600. */
  76601. this.onBeforeBlurObservable = new BABYLON.Observable();
  76602. /**
  76603. * An event triggered when the highlight layer has been blurred.
  76604. * @type {BABYLON.Observable}
  76605. */
  76606. this.onAfterBlurObservable = new BABYLON.Observable();
  76607. /**
  76608. * An event triggered when the glowing blurred texture is being merged in the scene.
  76609. * @type {BABYLON.Observable}
  76610. */
  76611. this.onBeforeComposeObservable = new BABYLON.Observable();
  76612. /**
  76613. * An event triggered when the glowing blurred texture has been merged in the scene.
  76614. * @type {BABYLON.Observable}
  76615. */
  76616. this.onAfterComposeObservable = new BABYLON.Observable();
  76617. /**
  76618. * An event triggered when the highlight layer changes its size.
  76619. * @type {BABYLON.Observable}
  76620. */
  76621. this.onSizeChangedObservable = new BABYLON.Observable();
  76622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76623. var engine = scene.getEngine();
  76624. this._engine = engine;
  76625. this._maxSize = this._engine.getCaps().maxTextureSize;
  76626. this._scene.highlightLayers.push(this);
  76627. // Warn on stencil.
  76628. if (!this._engine.isStencilEnable) {
  76629. 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 }");
  76630. }
  76631. // Adapt options
  76632. this._options = options || {
  76633. mainTextureRatio: 0.5,
  76634. blurTextureSizeRatio: 0.5,
  76635. blurHorizontalSize: 1.0,
  76636. blurVerticalSize: 1.0,
  76637. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76638. camera: null
  76639. };
  76640. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76641. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76642. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76643. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76644. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76645. // VBO
  76646. var vertices = [];
  76647. vertices.push(1, 1);
  76648. vertices.push(-1, 1);
  76649. vertices.push(-1, -1);
  76650. vertices.push(1, -1);
  76651. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76652. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76653. this._createIndexBuffer();
  76654. // Effect
  76655. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76656. // Render target
  76657. this.setMainTextureSize();
  76658. // Create Textures and post processes
  76659. this.createTextureAndPostProcesses();
  76660. }
  76661. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76662. /**
  76663. * Gets the horizontal size of the blur.
  76664. */
  76665. get: function () {
  76666. return this._horizontalBlurPostprocess.kernel;
  76667. },
  76668. /**
  76669. * Specifies the horizontal size of the blur.
  76670. */
  76671. set: function (value) {
  76672. this._horizontalBlurPostprocess.kernel = value;
  76673. },
  76674. enumerable: true,
  76675. configurable: true
  76676. });
  76677. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76678. /**
  76679. * Gets the vertical size of the blur.
  76680. */
  76681. get: function () {
  76682. return this._verticalBlurPostprocess.kernel;
  76683. },
  76684. /**
  76685. * Specifies the vertical size of the blur.
  76686. */
  76687. set: function (value) {
  76688. this._verticalBlurPostprocess.kernel = value;
  76689. },
  76690. enumerable: true,
  76691. configurable: true
  76692. });
  76693. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76694. /**
  76695. * Gets the camera attached to the layer.
  76696. */
  76697. get: function () {
  76698. return this._options.camera;
  76699. },
  76700. enumerable: true,
  76701. configurable: true
  76702. });
  76703. HighlightLayer.prototype._createIndexBuffer = function () {
  76704. var engine = this._scene.getEngine();
  76705. // Indices
  76706. var indices = [];
  76707. indices.push(0);
  76708. indices.push(1);
  76709. indices.push(2);
  76710. indices.push(0);
  76711. indices.push(2);
  76712. indices.push(3);
  76713. this._indexBuffer = engine.createIndexBuffer(indices);
  76714. };
  76715. HighlightLayer.prototype._rebuild = function () {
  76716. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76717. if (vb) {
  76718. vb._rebuild();
  76719. }
  76720. this._createIndexBuffer();
  76721. };
  76722. /**
  76723. * Creates the render target textures and post processes used in the highlight layer.
  76724. */
  76725. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76726. var _this = this;
  76727. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76728. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76729. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76730. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76731. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76732. width: this._mainTextureDesiredSize.width,
  76733. height: this._mainTextureDesiredSize.height
  76734. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76735. this._mainTexture.activeCamera = this._options.camera;
  76736. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76737. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76738. this._mainTexture.anisotropicFilteringLevel = 1;
  76739. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76740. this._mainTexture.renderParticles = false;
  76741. this._mainTexture.renderList = null;
  76742. this._mainTexture.ignoreCameraViewport = true;
  76743. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76744. width: blurTextureWidth,
  76745. height: blurTextureHeight
  76746. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76747. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76748. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76749. this._blurTexture.anisotropicFilteringLevel = 16;
  76750. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76751. this._blurTexture.renderParticles = false;
  76752. this._blurTexture.ignoreCameraViewport = true;
  76753. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76754. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76755. effect.setTexture("textureSampler", _this._mainTexture);
  76756. });
  76757. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76758. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76759. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76760. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76761. });
  76762. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76763. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76764. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76765. });
  76766. }
  76767. else {
  76768. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76769. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76770. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76771. });
  76772. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76773. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76774. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76775. });
  76776. }
  76777. this._mainTexture.onAfterUnbindObservable.add(function () {
  76778. _this.onBeforeBlurObservable.notifyObservers(_this);
  76779. var internalTexture = _this._blurTexture.getInternalTexture();
  76780. if (internalTexture) {
  76781. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76782. }
  76783. _this.onAfterBlurObservable.notifyObservers(_this);
  76784. });
  76785. // Custom render function
  76786. var renderSubMesh = function (subMesh) {
  76787. if (!_this._meshes) {
  76788. return;
  76789. }
  76790. var material = subMesh.getMaterial();
  76791. var mesh = subMesh.getRenderingMesh();
  76792. var scene = _this._scene;
  76793. var engine = scene.getEngine();
  76794. if (!material) {
  76795. return;
  76796. }
  76797. // Do not block in blend mode.
  76798. if (material.needAlphaBlendingForMesh(mesh)) {
  76799. return;
  76800. }
  76801. // Culling
  76802. engine.setState(material.backFaceCulling);
  76803. // Managing instances
  76804. var batch = mesh._getInstancesRenderList(subMesh._id);
  76805. if (batch.mustReturn) {
  76806. return;
  76807. }
  76808. // Excluded Mesh
  76809. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76810. return;
  76811. }
  76812. ;
  76813. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76814. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76815. var emissiveTexture = null;
  76816. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76817. emissiveTexture = material.emissiveTexture;
  76818. }
  76819. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76820. engine.enableEffect(_this._glowMapGenerationEffect);
  76821. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76822. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76823. if (highlightLayerMesh) {
  76824. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76825. }
  76826. else {
  76827. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76828. }
  76829. // Alpha test
  76830. if (material && material.needAlphaTesting()) {
  76831. var alphaTexture = material.getAlphaTestTexture();
  76832. if (alphaTexture) {
  76833. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76834. var textureMatrix = alphaTexture.getTextureMatrix();
  76835. if (textureMatrix) {
  76836. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76837. }
  76838. }
  76839. }
  76840. // Glow emissive only
  76841. if (emissiveTexture) {
  76842. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76843. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76844. }
  76845. // Bones
  76846. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76847. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76848. }
  76849. // Draw
  76850. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76851. }
  76852. else {
  76853. // Need to reset refresh rate of the shadowMap
  76854. _this._mainTexture.resetRefreshCounter();
  76855. }
  76856. };
  76857. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76858. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76859. var index;
  76860. var engine = _this._scene.getEngine();
  76861. if (depthOnlySubMeshes.length) {
  76862. engine.setColorWrite(false);
  76863. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76864. renderSubMesh(depthOnlySubMeshes.data[index]);
  76865. }
  76866. engine.setColorWrite(true);
  76867. }
  76868. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76869. renderSubMesh(opaqueSubMeshes.data[index]);
  76870. }
  76871. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76872. renderSubMesh(alphaTestSubMeshes.data[index]);
  76873. }
  76874. for (index = 0; index < transparentSubMeshes.length; index++) {
  76875. renderSubMesh(transparentSubMeshes.data[index]);
  76876. }
  76877. };
  76878. this._mainTexture.onClearObservable.add(function (engine) {
  76879. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76880. });
  76881. };
  76882. /**
  76883. * Checks for the readiness of the element composing the layer.
  76884. * @param subMesh the mesh to check for
  76885. * @param useInstances specify wether or not to use instances to render the mesh
  76886. * @param emissiveTexture the associated emissive texture used to generate the glow
  76887. * @return true if ready otherwise, false
  76888. */
  76889. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  76890. var material = subMesh.getMaterial();
  76891. if (!material) {
  76892. return false;
  76893. }
  76894. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  76895. return false;
  76896. }
  76897. var defines = [];
  76898. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76899. var mesh = subMesh.getMesh();
  76900. var uv1 = false;
  76901. var uv2 = false;
  76902. // Alpha test
  76903. if (material && material.needAlphaTesting()) {
  76904. var alphaTexture = material.getAlphaTestTexture();
  76905. if (alphaTexture) {
  76906. defines.push("#define ALPHATEST");
  76907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76908. alphaTexture.coordinatesIndex === 1) {
  76909. defines.push("#define DIFFUSEUV2");
  76910. uv2 = true;
  76911. }
  76912. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76913. defines.push("#define DIFFUSEUV1");
  76914. uv1 = true;
  76915. }
  76916. }
  76917. }
  76918. // Emissive
  76919. if (emissiveTexture) {
  76920. defines.push("#define EMISSIVE");
  76921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76922. emissiveTexture.coordinatesIndex === 1) {
  76923. defines.push("#define EMISSIVEUV2");
  76924. uv2 = true;
  76925. }
  76926. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76927. defines.push("#define EMISSIVEUV1");
  76928. uv1 = true;
  76929. }
  76930. }
  76931. if (uv1) {
  76932. attribs.push(BABYLON.VertexBuffer.UVKind);
  76933. defines.push("#define UV1");
  76934. }
  76935. if (uv2) {
  76936. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76937. defines.push("#define UV2");
  76938. }
  76939. // Bones
  76940. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76943. if (mesh.numBoneInfluencers > 4) {
  76944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76946. }
  76947. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76948. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76949. }
  76950. else {
  76951. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76952. }
  76953. // Instances
  76954. if (useInstances) {
  76955. defines.push("#define INSTANCES");
  76956. attribs.push("world0");
  76957. attribs.push("world1");
  76958. attribs.push("world2");
  76959. attribs.push("world3");
  76960. }
  76961. // Get correct effect
  76962. var join = defines.join("\n");
  76963. if (this._cachedDefines !== join) {
  76964. this._cachedDefines = join;
  76965. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  76966. }
  76967. return this._glowMapGenerationEffect.isReady();
  76968. };
  76969. /**
  76970. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  76971. */
  76972. HighlightLayer.prototype.render = function () {
  76973. var currentEffect = this._glowMapMergeEffect;
  76974. // Check
  76975. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  76976. return;
  76977. var engine = this._scene.getEngine();
  76978. this.onBeforeComposeObservable.notifyObservers(this);
  76979. // Render
  76980. engine.enableEffect(currentEffect);
  76981. engine.setState(false);
  76982. // Cache
  76983. var previousStencilBuffer = engine.getStencilBuffer();
  76984. var previousStencilFunction = engine.getStencilFunction();
  76985. var previousStencilMask = engine.getStencilMask();
  76986. var previousStencilOperationPass = engine.getStencilOperationPass();
  76987. var previousStencilOperationFail = engine.getStencilOperationFail();
  76988. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  76989. var previousAlphaMode = engine.getAlphaMode();
  76990. // Texture
  76991. currentEffect.setTexture("textureSampler", this._blurTexture);
  76992. // VBOs
  76993. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76994. // Stencil operations
  76995. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  76996. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  76997. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  76998. // Draw order
  76999. engine.setAlphaMode(this._options.alphaBlendingMode);
  77000. engine.setStencilMask(0x00);
  77001. engine.setStencilBuffer(true);
  77002. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77003. if (this.outerGlow) {
  77004. currentEffect.setFloat("offset", 0);
  77005. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77006. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77007. }
  77008. if (this.innerGlow) {
  77009. currentEffect.setFloat("offset", 1);
  77010. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77011. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77012. }
  77013. // Restore Cache
  77014. engine.setStencilFunction(previousStencilFunction);
  77015. engine.setStencilMask(previousStencilMask);
  77016. engine.setAlphaMode(previousAlphaMode);
  77017. engine.setStencilBuffer(previousStencilBuffer);
  77018. engine.setStencilOperationPass(previousStencilOperationPass);
  77019. engine.setStencilOperationFail(previousStencilOperationFail);
  77020. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77021. engine._stencilState.reset();
  77022. this.onAfterComposeObservable.notifyObservers(this);
  77023. // Handle size changes.
  77024. var size = this._mainTexture.getSize();
  77025. this.setMainTextureSize();
  77026. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77027. // Recreate RTT and post processes on size change.
  77028. this.onSizeChangedObservable.notifyObservers(this);
  77029. this.disposeTextureAndPostProcesses();
  77030. this.createTextureAndPostProcesses();
  77031. }
  77032. };
  77033. /**
  77034. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77035. * @param mesh The mesh to exclude from the highlight layer
  77036. */
  77037. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77038. if (!this._excludedMeshes) {
  77039. return;
  77040. }
  77041. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77042. if (!meshExcluded) {
  77043. this._excludedMeshes[mesh.uniqueId] = {
  77044. mesh: mesh,
  77045. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77046. mesh.getEngine().setStencilBuffer(false);
  77047. }),
  77048. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77049. mesh.getEngine().setStencilBuffer(true);
  77050. }),
  77051. };
  77052. }
  77053. };
  77054. /**
  77055. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77056. * @param mesh The mesh to highlight
  77057. */
  77058. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77059. if (!this._excludedMeshes) {
  77060. return;
  77061. }
  77062. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77063. if (meshExcluded) {
  77064. if (meshExcluded.beforeRender) {
  77065. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77066. }
  77067. if (meshExcluded.afterRender) {
  77068. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77069. }
  77070. }
  77071. this._excludedMeshes[mesh.uniqueId] = null;
  77072. };
  77073. /**
  77074. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77075. * @param mesh The mesh to highlight
  77076. * @param color The color of the highlight
  77077. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77078. */
  77079. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77080. var _this = this;
  77081. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77082. if (!this._meshes) {
  77083. return;
  77084. }
  77085. var meshHighlight = this._meshes[mesh.uniqueId];
  77086. if (meshHighlight) {
  77087. meshHighlight.color = color;
  77088. }
  77089. else {
  77090. this._meshes[mesh.uniqueId] = {
  77091. mesh: mesh,
  77092. color: color,
  77093. // Lambda required for capture due to Observable this context
  77094. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77095. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77096. _this.defaultStencilReference(mesh);
  77097. }
  77098. else {
  77099. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77100. }
  77101. }),
  77102. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77103. glowEmissiveOnly: glowEmissiveOnly
  77104. };
  77105. }
  77106. this._shouldRender = true;
  77107. };
  77108. /**
  77109. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77110. * @param mesh The mesh to highlight
  77111. */
  77112. HighlightLayer.prototype.removeMesh = function (mesh) {
  77113. if (!this._meshes) {
  77114. return;
  77115. }
  77116. var meshHighlight = this._meshes[mesh.uniqueId];
  77117. if (meshHighlight) {
  77118. if (meshHighlight.observerHighlight) {
  77119. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77120. }
  77121. if (meshHighlight.observerDefault) {
  77122. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77123. }
  77124. delete this._meshes[mesh.uniqueId];
  77125. }
  77126. this._shouldRender = false;
  77127. for (var meshHighlightToCheck in this._meshes) {
  77128. if (this._meshes[meshHighlightToCheck]) {
  77129. this._shouldRender = true;
  77130. break;
  77131. }
  77132. }
  77133. };
  77134. /**
  77135. * Returns true if the layer contains information to display, otherwise false.
  77136. */
  77137. HighlightLayer.prototype.shouldRender = function () {
  77138. return this.isEnabled && this._shouldRender;
  77139. };
  77140. /**
  77141. * Sets the main texture desired size which is the closest power of two
  77142. * of the engine canvas size.
  77143. */
  77144. HighlightLayer.prototype.setMainTextureSize = function () {
  77145. if (this._options.mainTextureFixedSize) {
  77146. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77147. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77148. }
  77149. else {
  77150. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77151. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77152. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77153. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77154. }
  77155. };
  77156. /**
  77157. * Force the stencil to the normal expected value for none glowing parts
  77158. */
  77159. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77160. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77161. };
  77162. /**
  77163. * Dispose only the render target textures and post process.
  77164. */
  77165. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77166. this._blurTexture.dispose();
  77167. this._mainTexture.dispose();
  77168. this._downSamplePostprocess.dispose();
  77169. this._horizontalBlurPostprocess.dispose();
  77170. this._verticalBlurPostprocess.dispose();
  77171. };
  77172. /**
  77173. * Dispose the highlight layer and free resources.
  77174. */
  77175. HighlightLayer.prototype.dispose = function () {
  77176. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77177. if (vertexBuffer) {
  77178. vertexBuffer.dispose();
  77179. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77180. }
  77181. if (this._indexBuffer) {
  77182. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77183. this._indexBuffer = null;
  77184. }
  77185. // Clean textures and post processes
  77186. this.disposeTextureAndPostProcesses();
  77187. if (this._meshes) {
  77188. // Clean mesh references
  77189. for (var id in this._meshes) {
  77190. var meshHighlight = this._meshes[id];
  77191. if (meshHighlight && meshHighlight.mesh) {
  77192. if (meshHighlight.observerHighlight) {
  77193. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77194. }
  77195. if (meshHighlight.observerDefault) {
  77196. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77197. }
  77198. }
  77199. }
  77200. this._meshes = null;
  77201. }
  77202. if (this._excludedMeshes) {
  77203. for (var id in this._excludedMeshes) {
  77204. var meshHighlight = this._excludedMeshes[id];
  77205. if (meshHighlight) {
  77206. if (meshHighlight.beforeRender) {
  77207. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77208. }
  77209. if (meshHighlight.afterRender) {
  77210. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77211. }
  77212. }
  77213. }
  77214. this._excludedMeshes = null;
  77215. }
  77216. // Remove from scene
  77217. var index = this._scene.highlightLayers.indexOf(this, 0);
  77218. if (index > -1) {
  77219. this._scene.highlightLayers.splice(index, 1);
  77220. }
  77221. // Callback
  77222. this.onDisposeObservable.notifyObservers(this);
  77223. this.onDisposeObservable.clear();
  77224. this.onBeforeRenderMainTextureObservable.clear();
  77225. this.onBeforeBlurObservable.clear();
  77226. this.onBeforeComposeObservable.clear();
  77227. this.onAfterComposeObservable.clear();
  77228. this.onSizeChangedObservable.clear();
  77229. };
  77230. /**
  77231. * The neutral color used during the preparation of the glow effect.
  77232. * This is black by default as the blend operation is a blend operation.
  77233. */
  77234. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77235. /**
  77236. * Stencil value used for glowing meshes.
  77237. */
  77238. HighlightLayer.glowingMeshStencilReference = 0x02;
  77239. /**
  77240. * Stencil value used for the other meshes in the scene.
  77241. */
  77242. HighlightLayer.normalMeshStencilReference = 0x01;
  77243. return HighlightLayer;
  77244. }());
  77245. BABYLON.HighlightLayer = HighlightLayer;
  77246. })(BABYLON || (BABYLON = {}));
  77247. //# sourceMappingURL=babylon.highlightlayer.js.map
  77248. var BABYLON;
  77249. (function (BABYLON) {
  77250. var AssetTaskState;
  77251. (function (AssetTaskState) {
  77252. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77253. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77254. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77255. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77256. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77257. var AbstractAssetTask = /** @class */ (function () {
  77258. function AbstractAssetTask(name) {
  77259. this.name = name;
  77260. this.isCompleted = false;
  77261. this.taskState = AssetTaskState.INIT;
  77262. }
  77263. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77264. var _this = this;
  77265. this.taskState = AssetTaskState.RUNNING;
  77266. this.runTask(scene, function () {
  77267. _this.onDoneCallback(onSuccess, onError);
  77268. }, function (msg, exception) {
  77269. _this.onErrorCallback(onError, msg, exception);
  77270. });
  77271. };
  77272. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77273. throw new Error("runTask is not implemented");
  77274. };
  77275. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77276. this.taskState = AssetTaskState.ERROR;
  77277. this.errorObject = {
  77278. message: message,
  77279. exception: exception
  77280. };
  77281. if (this.onError) {
  77282. this.onError(this, message, exception);
  77283. }
  77284. onError();
  77285. };
  77286. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77287. try {
  77288. this.taskState = AssetTaskState.DONE;
  77289. this.isCompleted = true;
  77290. if (this.onSuccess) {
  77291. this.onSuccess(this);
  77292. }
  77293. onSuccess();
  77294. }
  77295. catch (e) {
  77296. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77297. }
  77298. };
  77299. return AbstractAssetTask;
  77300. }());
  77301. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77302. var AssetsProgressEvent = /** @class */ (function () {
  77303. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77304. this.remainingCount = remainingCount;
  77305. this.totalCount = totalCount;
  77306. this.task = task;
  77307. }
  77308. return AssetsProgressEvent;
  77309. }());
  77310. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77311. var MeshAssetTask = /** @class */ (function (_super) {
  77312. __extends(MeshAssetTask, _super);
  77313. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  77314. var _this = _super.call(this, name) || this;
  77315. _this.name = name;
  77316. _this.meshesNames = meshesNames;
  77317. _this.rootUrl = rootUrl;
  77318. _this.sceneFilename = sceneFilename;
  77319. return _this;
  77320. }
  77321. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77322. var _this = this;
  77323. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77324. _this.loadedMeshes = meshes;
  77325. _this.loadedParticleSystems = particleSystems;
  77326. _this.loadedSkeletons = skeletons;
  77327. onSuccess();
  77328. }, null, function (scene, message, exception) {
  77329. onError(message, exception);
  77330. });
  77331. };
  77332. return MeshAssetTask;
  77333. }(AbstractAssetTask));
  77334. BABYLON.MeshAssetTask = MeshAssetTask;
  77335. var TextFileAssetTask = /** @class */ (function (_super) {
  77336. __extends(TextFileAssetTask, _super);
  77337. function TextFileAssetTask(name, url) {
  77338. var _this = _super.call(this, name) || this;
  77339. _this.name = name;
  77340. _this.url = url;
  77341. return _this;
  77342. }
  77343. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77344. var _this = this;
  77345. scene._loadFile(this.url, function (data) {
  77346. _this.text = data;
  77347. onSuccess();
  77348. }, undefined, false, true, function (request, exception) {
  77349. if (request) {
  77350. onError(request.status + " " + request.statusText, exception);
  77351. }
  77352. });
  77353. };
  77354. return TextFileAssetTask;
  77355. }(AbstractAssetTask));
  77356. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77357. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77358. __extends(BinaryFileAssetTask, _super);
  77359. function BinaryFileAssetTask(name, url) {
  77360. var _this = _super.call(this, name) || this;
  77361. _this.name = name;
  77362. _this.url = url;
  77363. return _this;
  77364. }
  77365. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77366. var _this = this;
  77367. scene._loadFile(this.url, function (data) {
  77368. _this.data = data;
  77369. onSuccess();
  77370. }, undefined, true, true, function (request, exception) {
  77371. if (request) {
  77372. onError(request.status + " " + request.statusText, exception);
  77373. }
  77374. });
  77375. };
  77376. return BinaryFileAssetTask;
  77377. }(AbstractAssetTask));
  77378. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77379. var ImageAssetTask = /** @class */ (function (_super) {
  77380. __extends(ImageAssetTask, _super);
  77381. function ImageAssetTask(name, url) {
  77382. var _this = _super.call(this, name) || this;
  77383. _this.name = name;
  77384. _this.url = url;
  77385. return _this;
  77386. }
  77387. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77388. var _this = this;
  77389. var img = new Image();
  77390. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77391. img.onload = function () {
  77392. _this.image = img;
  77393. onSuccess();
  77394. };
  77395. img.onerror = function (err) {
  77396. onError("Error loading image", err);
  77397. };
  77398. img.src = this.url;
  77399. };
  77400. return ImageAssetTask;
  77401. }(AbstractAssetTask));
  77402. BABYLON.ImageAssetTask = ImageAssetTask;
  77403. var TextureAssetTask = /** @class */ (function (_super) {
  77404. __extends(TextureAssetTask, _super);
  77405. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  77406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77407. var _this = _super.call(this, name) || this;
  77408. _this.name = name;
  77409. _this.url = url;
  77410. _this.noMipmap = noMipmap;
  77411. _this.invertY = invertY;
  77412. _this.samplingMode = samplingMode;
  77413. return _this;
  77414. }
  77415. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77416. var onload = function () {
  77417. onSuccess();
  77418. };
  77419. var onerror = function (message, exception) {
  77420. onError(message, exception);
  77421. };
  77422. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77423. };
  77424. return TextureAssetTask;
  77425. }(AbstractAssetTask));
  77426. BABYLON.TextureAssetTask = TextureAssetTask;
  77427. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77428. __extends(CubeTextureAssetTask, _super);
  77429. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  77430. var _this = _super.call(this, name) || this;
  77431. _this.name = name;
  77432. _this.url = url;
  77433. _this.extensions = extensions;
  77434. _this.noMipmap = noMipmap;
  77435. _this.files = files;
  77436. return _this;
  77437. }
  77438. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77439. var onload = function () {
  77440. onSuccess();
  77441. };
  77442. var onerror = function (message, exception) {
  77443. onError(message, exception);
  77444. };
  77445. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77446. };
  77447. return CubeTextureAssetTask;
  77448. }(AbstractAssetTask));
  77449. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77450. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77451. __extends(HDRCubeTextureAssetTask, _super);
  77452. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77453. if (noMipmap === void 0) { noMipmap = false; }
  77454. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77455. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77456. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77457. var _this = _super.call(this, name) || this;
  77458. _this.name = name;
  77459. _this.url = url;
  77460. _this.size = size;
  77461. _this.noMipmap = noMipmap;
  77462. _this.generateHarmonics = generateHarmonics;
  77463. _this.useInGammaSpace = useInGammaSpace;
  77464. _this.usePMREMGenerator = usePMREMGenerator;
  77465. return _this;
  77466. }
  77467. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77468. var onload = function () {
  77469. onSuccess();
  77470. };
  77471. var onerror = function (message, exception) {
  77472. onError(message, exception);
  77473. };
  77474. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  77475. };
  77476. return HDRCubeTextureAssetTask;
  77477. }(AbstractAssetTask));
  77478. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  77479. var AssetsManager = /** @class */ (function () {
  77480. function AssetsManager(scene) {
  77481. this._isLoading = false;
  77482. this.tasks = new Array();
  77483. this.waitingTasksCount = 0;
  77484. //Observables
  77485. this.onTaskSuccessObservable = new BABYLON.Observable();
  77486. this.onTaskErrorObservable = new BABYLON.Observable();
  77487. this.onTasksDoneObservable = new BABYLON.Observable();
  77488. this.onProgressObservable = new BABYLON.Observable();
  77489. this.useDefaultLoadingScreen = true;
  77490. this._scene = scene;
  77491. }
  77492. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77493. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77494. this.tasks.push(task);
  77495. return task;
  77496. };
  77497. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77498. var task = new TextFileAssetTask(taskName, url);
  77499. this.tasks.push(task);
  77500. return task;
  77501. };
  77502. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77503. var task = new BinaryFileAssetTask(taskName, url);
  77504. this.tasks.push(task);
  77505. return task;
  77506. };
  77507. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77508. var task = new ImageAssetTask(taskName, url);
  77509. this.tasks.push(task);
  77510. return task;
  77511. };
  77512. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  77513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77514. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  77515. this.tasks.push(task);
  77516. return task;
  77517. };
  77518. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  77519. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  77520. this.tasks.push(task);
  77521. return task;
  77522. };
  77523. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77524. if (noMipmap === void 0) { noMipmap = false; }
  77525. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77526. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77527. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77528. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  77529. this.tasks.push(task);
  77530. return task;
  77531. };
  77532. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  77533. this.waitingTasksCount--;
  77534. try {
  77535. if (this.onProgress) {
  77536. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  77537. }
  77538. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  77539. }
  77540. catch (e) {
  77541. BABYLON.Tools.Error("Error running progress callbacks.");
  77542. console.log(e);
  77543. }
  77544. if (this.waitingTasksCount === 0) {
  77545. try {
  77546. if (this.onFinish) {
  77547. this.onFinish(this.tasks);
  77548. }
  77549. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77550. }
  77551. catch (e) {
  77552. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  77553. console.log(e);
  77554. }
  77555. this._isLoading = false;
  77556. this._scene.getEngine().hideLoadingUI();
  77557. }
  77558. };
  77559. AssetsManager.prototype._runTask = function (task) {
  77560. var _this = this;
  77561. var done = function () {
  77562. try {
  77563. if (_this.onTaskSuccess) {
  77564. _this.onTaskSuccess(task);
  77565. }
  77566. _this.onTaskSuccessObservable.notifyObservers(task);
  77567. _this._decreaseWaitingTasksCount(task);
  77568. }
  77569. catch (e) {
  77570. error("Error executing task success callbacks", e);
  77571. }
  77572. };
  77573. var error = function (message, exception) {
  77574. task.errorObject = task.errorObject || {
  77575. message: message,
  77576. exception: exception
  77577. };
  77578. if (_this.onTaskError) {
  77579. _this.onTaskError(task);
  77580. }
  77581. _this.onTaskErrorObservable.notifyObservers(task);
  77582. _this._decreaseWaitingTasksCount(task);
  77583. };
  77584. task.run(this._scene, done, error);
  77585. };
  77586. AssetsManager.prototype.reset = function () {
  77587. this._isLoading = false;
  77588. this.tasks = new Array();
  77589. return this;
  77590. };
  77591. AssetsManager.prototype.load = function () {
  77592. if (this._isLoading) {
  77593. return this;
  77594. }
  77595. this._isLoading = true;
  77596. this.waitingTasksCount = this.tasks.length;
  77597. if (this.waitingTasksCount === 0) {
  77598. if (this.onFinish) {
  77599. this.onFinish(this.tasks);
  77600. }
  77601. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77602. this._isLoading = false;
  77603. return this;
  77604. }
  77605. if (this.useDefaultLoadingScreen) {
  77606. this._scene.getEngine().displayLoadingUI();
  77607. }
  77608. for (var index = 0; index < this.tasks.length; index++) {
  77609. var task = this.tasks[index];
  77610. this._runTask(task);
  77611. }
  77612. return this;
  77613. };
  77614. return AssetsManager;
  77615. }());
  77616. BABYLON.AssetsManager = AssetsManager;
  77617. })(BABYLON || (BABYLON = {}));
  77618. //# sourceMappingURL=babylon.assetsManager.js.map
  77619. var BABYLON;
  77620. (function (BABYLON) {
  77621. var serializedGeometries = [];
  77622. var serializeGeometry = function (geometry, serializationGeometries) {
  77623. if (serializedGeometries[geometry.id]) {
  77624. return;
  77625. }
  77626. if (geometry.doNotSerialize) {
  77627. return;
  77628. }
  77629. if (geometry instanceof BABYLON.BoxGeometry) {
  77630. serializationGeometries.boxes.push(geometry.serialize());
  77631. }
  77632. else if (geometry instanceof BABYLON.SphereGeometry) {
  77633. serializationGeometries.spheres.push(geometry.serialize());
  77634. }
  77635. else if (geometry instanceof BABYLON.CylinderGeometry) {
  77636. serializationGeometries.cylinders.push(geometry.serialize());
  77637. }
  77638. else if (geometry instanceof BABYLON.TorusGeometry) {
  77639. serializationGeometries.toruses.push(geometry.serialize());
  77640. }
  77641. else if (geometry instanceof BABYLON.GroundGeometry) {
  77642. serializationGeometries.grounds.push(geometry.serialize());
  77643. }
  77644. else if (geometry instanceof BABYLON.Plane) {
  77645. serializationGeometries.planes.push(geometry.serialize());
  77646. }
  77647. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  77648. serializationGeometries.torusKnots.push(geometry.serialize());
  77649. }
  77650. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  77651. throw new Error("Unknown primitive type");
  77652. }
  77653. else {
  77654. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  77655. }
  77656. serializedGeometries[geometry.id] = true;
  77657. };
  77658. var serializeMesh = function (mesh, serializationScene) {
  77659. var serializationObject = {};
  77660. // Geometry
  77661. var geometry = mesh._geometry;
  77662. if (geometry) {
  77663. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  77664. // 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
  77665. serializeGeometry(geometry, serializationScene.geometries);
  77666. }
  77667. }
  77668. // Custom
  77669. if (mesh.serialize) {
  77670. mesh.serialize(serializationObject);
  77671. }
  77672. return serializationObject;
  77673. };
  77674. var finalizeSingleMesh = function (mesh, serializationObject) {
  77675. //only works if the mesh is already loaded
  77676. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77677. //serialize material
  77678. if (mesh.material) {
  77679. if (mesh.material instanceof BABYLON.StandardMaterial) {
  77680. serializationObject.materials = serializationObject.materials || [];
  77681. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77682. serializationObject.materials.push(mesh.material.serialize());
  77683. }
  77684. }
  77685. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  77686. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  77687. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77688. serializationObject.multiMaterials.push(mesh.material.serialize());
  77689. }
  77690. }
  77691. }
  77692. //serialize geometry
  77693. var geometry = mesh._geometry;
  77694. if (geometry) {
  77695. if (!serializationObject.geometries) {
  77696. serializationObject.geometries = {};
  77697. serializationObject.geometries.boxes = [];
  77698. serializationObject.geometries.spheres = [];
  77699. serializationObject.geometries.cylinders = [];
  77700. serializationObject.geometries.toruses = [];
  77701. serializationObject.geometries.grounds = [];
  77702. serializationObject.geometries.planes = [];
  77703. serializationObject.geometries.torusKnots = [];
  77704. serializationObject.geometries.vertexData = [];
  77705. }
  77706. serializeGeometry(geometry, serializationObject.geometries);
  77707. }
  77708. // Skeletons
  77709. if (mesh.skeleton) {
  77710. serializationObject.skeletons = serializationObject.skeletons || [];
  77711. serializationObject.skeletons.push(mesh.skeleton.serialize());
  77712. }
  77713. //serialize the actual mesh
  77714. serializationObject.meshes = serializationObject.meshes || [];
  77715. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77716. }
  77717. };
  77718. var SceneSerializer = /** @class */ (function () {
  77719. function SceneSerializer() {
  77720. }
  77721. SceneSerializer.ClearCache = function () {
  77722. serializedGeometries = [];
  77723. };
  77724. SceneSerializer.Serialize = function (scene) {
  77725. var serializationObject = {};
  77726. SceneSerializer.ClearCache();
  77727. // Scene
  77728. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  77729. serializationObject.autoClear = scene.autoClear;
  77730. serializationObject.clearColor = scene.clearColor.asArray();
  77731. serializationObject.ambientColor = scene.ambientColor.asArray();
  77732. serializationObject.gravity = scene.gravity.asArray();
  77733. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  77734. serializationObject.workerCollisions = scene.workerCollisions;
  77735. // Fog
  77736. if (scene.fogMode && scene.fogMode !== 0) {
  77737. serializationObject.fogMode = scene.fogMode;
  77738. serializationObject.fogColor = scene.fogColor.asArray();
  77739. serializationObject.fogStart = scene.fogStart;
  77740. serializationObject.fogEnd = scene.fogEnd;
  77741. serializationObject.fogDensity = scene.fogDensity;
  77742. }
  77743. //Physics
  77744. if (scene.isPhysicsEnabled()) {
  77745. var physicEngine = scene.getPhysicsEngine();
  77746. if (physicEngine) {
  77747. serializationObject.physicsEnabled = true;
  77748. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  77749. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  77750. }
  77751. }
  77752. // Metadata
  77753. if (scene.metadata) {
  77754. serializationObject.metadata = scene.metadata;
  77755. }
  77756. // Morph targets
  77757. serializationObject.morphTargetManagers = [];
  77758. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  77759. var abstractMesh = _a[_i];
  77760. var manager = abstractMesh.morphTargetManager;
  77761. if (manager) {
  77762. serializationObject.morphTargetManagers.push(manager.serialize());
  77763. }
  77764. }
  77765. // Lights
  77766. serializationObject.lights = [];
  77767. var index;
  77768. var light;
  77769. for (index = 0; index < scene.lights.length; index++) {
  77770. light = scene.lights[index];
  77771. if (!light.doNotSerialize) {
  77772. serializationObject.lights.push(light.serialize());
  77773. }
  77774. }
  77775. // Cameras
  77776. serializationObject.cameras = [];
  77777. for (index = 0; index < scene.cameras.length; index++) {
  77778. var camera = scene.cameras[index];
  77779. if (!camera.doNotSerialize) {
  77780. serializationObject.cameras.push(camera.serialize());
  77781. }
  77782. }
  77783. if (scene.activeCamera) {
  77784. serializationObject.activeCameraID = scene.activeCamera.id;
  77785. }
  77786. // Animations
  77787. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  77788. // Materials
  77789. serializationObject.materials = [];
  77790. serializationObject.multiMaterials = [];
  77791. var material;
  77792. for (index = 0; index < scene.materials.length; index++) {
  77793. material = scene.materials[index];
  77794. if (!material.doNotSerialize) {
  77795. serializationObject.materials.push(material.serialize());
  77796. }
  77797. }
  77798. // MultiMaterials
  77799. serializationObject.multiMaterials = [];
  77800. for (index = 0; index < scene.multiMaterials.length; index++) {
  77801. var multiMaterial = scene.multiMaterials[index];
  77802. serializationObject.multiMaterials.push(multiMaterial.serialize());
  77803. }
  77804. // Environment texture
  77805. if (scene.environmentTexture) {
  77806. serializationObject.environmentTexture = scene.environmentTexture.name;
  77807. }
  77808. // Skeletons
  77809. serializationObject.skeletons = [];
  77810. for (index = 0; index < scene.skeletons.length; index++) {
  77811. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  77812. }
  77813. // Transform nodes
  77814. serializationObject.transformNodes = [];
  77815. for (index = 0; index < scene.transformNodes.length; index++) {
  77816. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  77817. }
  77818. // Geometries
  77819. serializationObject.geometries = {};
  77820. serializationObject.geometries.boxes = [];
  77821. serializationObject.geometries.spheres = [];
  77822. serializationObject.geometries.cylinders = [];
  77823. serializationObject.geometries.toruses = [];
  77824. serializationObject.geometries.grounds = [];
  77825. serializationObject.geometries.planes = [];
  77826. serializationObject.geometries.torusKnots = [];
  77827. serializationObject.geometries.vertexData = [];
  77828. serializedGeometries = [];
  77829. var geometries = scene.getGeometries();
  77830. for (index = 0; index < geometries.length; index++) {
  77831. var geometry = geometries[index];
  77832. if (geometry.isReady()) {
  77833. serializeGeometry(geometry, serializationObject.geometries);
  77834. }
  77835. }
  77836. // Meshes
  77837. serializationObject.meshes = [];
  77838. for (index = 0; index < scene.meshes.length; index++) {
  77839. var abstractMesh = scene.meshes[index];
  77840. if (abstractMesh instanceof BABYLON.Mesh) {
  77841. var mesh = abstractMesh;
  77842. if (!mesh.doNotSerialize) {
  77843. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77844. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77845. }
  77846. }
  77847. }
  77848. }
  77849. // Particles Systems
  77850. serializationObject.particleSystems = [];
  77851. for (index = 0; index < scene.particleSystems.length; index++) {
  77852. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  77853. }
  77854. // Lens flares
  77855. serializationObject.lensFlareSystems = [];
  77856. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  77857. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  77858. }
  77859. // Shadows
  77860. serializationObject.shadowGenerators = [];
  77861. for (index = 0; index < scene.lights.length; index++) {
  77862. light = scene.lights[index];
  77863. var shadowGenerator = light.getShadowGenerator();
  77864. if (shadowGenerator) {
  77865. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77866. }
  77867. }
  77868. // Action Manager
  77869. if (scene.actionManager) {
  77870. serializationObject.actions = scene.actionManager.serialize("scene");
  77871. }
  77872. // Audio
  77873. serializationObject.sounds = [];
  77874. for (index = 0; index < scene.soundTracks.length; index++) {
  77875. var soundtrack = scene.soundTracks[index];
  77876. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  77877. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  77878. }
  77879. }
  77880. return serializationObject;
  77881. };
  77882. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  77883. if (withParents === void 0) { withParents = false; }
  77884. if (withChildren === void 0) { withChildren = false; }
  77885. var serializationObject = {};
  77886. SceneSerializer.ClearCache();
  77887. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  77888. if (withParents || withChildren) {
  77889. //deliberate for loop! not for each, appended should be processed as well.
  77890. for (var i = 0; i < toSerialize.length; ++i) {
  77891. if (withChildren) {
  77892. toSerialize[i].getDescendants().forEach(function (node) {
  77893. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  77894. toSerialize.push(node);
  77895. }
  77896. });
  77897. }
  77898. //make sure the array doesn't contain the object already
  77899. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  77900. toSerialize.push(toSerialize[i].parent);
  77901. }
  77902. }
  77903. }
  77904. toSerialize.forEach(function (mesh) {
  77905. finalizeSingleMesh(mesh, serializationObject);
  77906. });
  77907. return serializationObject;
  77908. };
  77909. return SceneSerializer;
  77910. }());
  77911. BABYLON.SceneSerializer = SceneSerializer;
  77912. })(BABYLON || (BABYLON = {}));
  77913. //# sourceMappingURL=babylon.sceneSerializer.js.map
  77914. var BABYLON;
  77915. (function (BABYLON) {
  77916. var ReflectionProbe = /** @class */ (function () {
  77917. function ReflectionProbe(name, size, scene, generateMipMaps) {
  77918. if (generateMipMaps === void 0) { generateMipMaps = true; }
  77919. var _this = this;
  77920. this.name = name;
  77921. this._viewMatrix = BABYLON.Matrix.Identity();
  77922. this._target = BABYLON.Vector3.Zero();
  77923. this._add = BABYLON.Vector3.Zero();
  77924. this.invertYAxis = false;
  77925. this.position = BABYLON.Vector3.Zero();
  77926. this._scene = scene;
  77927. this._scene.reflectionProbes.push(this);
  77928. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  77929. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  77930. switch (faceIndex) {
  77931. case 0:
  77932. _this._add.copyFromFloats(1, 0, 0);
  77933. break;
  77934. case 1:
  77935. _this._add.copyFromFloats(-1, 0, 0);
  77936. break;
  77937. case 2:
  77938. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  77939. break;
  77940. case 3:
  77941. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  77942. break;
  77943. case 4:
  77944. _this._add.copyFromFloats(0, 0, 1);
  77945. break;
  77946. case 5:
  77947. _this._add.copyFromFloats(0, 0, -1);
  77948. break;
  77949. }
  77950. if (_this._attachedMesh) {
  77951. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  77952. }
  77953. _this.position.addToRef(_this._add, _this._target);
  77954. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  77955. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  77956. scene._forcedViewPosition = _this.position;
  77957. });
  77958. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  77959. scene._forcedViewPosition = null;
  77960. scene.updateTransformMatrix(true);
  77961. });
  77962. if (scene.activeCamera) {
  77963. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77964. }
  77965. }
  77966. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  77967. get: function () {
  77968. return this._renderTargetTexture.samples;
  77969. },
  77970. set: function (value) {
  77971. this._renderTargetTexture.samples = value;
  77972. },
  77973. enumerable: true,
  77974. configurable: true
  77975. });
  77976. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  77977. get: function () {
  77978. return this._renderTargetTexture.refreshRate;
  77979. },
  77980. set: function (value) {
  77981. this._renderTargetTexture.refreshRate = value;
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. ReflectionProbe.prototype.getScene = function () {
  77987. return this._scene;
  77988. };
  77989. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  77990. get: function () {
  77991. return this._renderTargetTexture;
  77992. },
  77993. enumerable: true,
  77994. configurable: true
  77995. });
  77996. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  77997. get: function () {
  77998. return this._renderTargetTexture.renderList;
  77999. },
  78000. enumerable: true,
  78001. configurable: true
  78002. });
  78003. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78004. this._attachedMesh = mesh;
  78005. };
  78006. /**
  78007. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78008. *
  78009. * @param renderingGroupId The rendering group id corresponding to its index
  78010. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78011. */
  78012. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78013. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78014. };
  78015. ReflectionProbe.prototype.dispose = function () {
  78016. var index = this._scene.reflectionProbes.indexOf(this);
  78017. if (index !== -1) {
  78018. // Remove from the scene if found
  78019. this._scene.reflectionProbes.splice(index, 1);
  78020. }
  78021. if (this._renderTargetTexture) {
  78022. this._renderTargetTexture.dispose();
  78023. this._renderTargetTexture = null;
  78024. }
  78025. };
  78026. return ReflectionProbe;
  78027. }());
  78028. BABYLON.ReflectionProbe = ReflectionProbe;
  78029. })(BABYLON || (BABYLON = {}));
  78030. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78031. var BABYLON;
  78032. (function (BABYLON) {
  78033. var Layer = /** @class */ (function () {
  78034. function Layer(name, imgUrl, scene, isBackground, color) {
  78035. this.name = name;
  78036. this.scale = new BABYLON.Vector2(1, 1);
  78037. this.offset = new BABYLON.Vector2(0, 0);
  78038. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78039. this.layerMask = 0x0FFFFFFF;
  78040. this._vertexBuffers = {};
  78041. // Events
  78042. /**
  78043. * An event triggered when the layer is disposed.
  78044. * @type {BABYLON.Observable}
  78045. */
  78046. this.onDisposeObservable = new BABYLON.Observable();
  78047. /**
  78048. * An event triggered before rendering the scene
  78049. * @type {BABYLON.Observable}
  78050. */
  78051. this.onBeforeRenderObservable = new BABYLON.Observable();
  78052. /**
  78053. * An event triggered after rendering the scene
  78054. * @type {BABYLON.Observable}
  78055. */
  78056. this.onAfterRenderObservable = new BABYLON.Observable();
  78057. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78058. this.isBackground = isBackground === undefined ? true : isBackground;
  78059. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78060. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78061. this._scene.layers.push(this);
  78062. var engine = this._scene.getEngine();
  78063. // VBO
  78064. var vertices = [];
  78065. vertices.push(1, 1);
  78066. vertices.push(-1, 1);
  78067. vertices.push(-1, -1);
  78068. vertices.push(1, -1);
  78069. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78071. this._createIndexBuffer();
  78072. // Effects
  78073. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78074. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78075. }
  78076. Object.defineProperty(Layer.prototype, "onDispose", {
  78077. set: function (callback) {
  78078. if (this._onDisposeObserver) {
  78079. this.onDisposeObservable.remove(this._onDisposeObserver);
  78080. }
  78081. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78082. },
  78083. enumerable: true,
  78084. configurable: true
  78085. });
  78086. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78087. set: function (callback) {
  78088. if (this._onBeforeRenderObserver) {
  78089. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78090. }
  78091. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78092. },
  78093. enumerable: true,
  78094. configurable: true
  78095. });
  78096. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78097. set: function (callback) {
  78098. if (this._onAfterRenderObserver) {
  78099. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78100. }
  78101. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78102. },
  78103. enumerable: true,
  78104. configurable: true
  78105. });
  78106. Layer.prototype._createIndexBuffer = function () {
  78107. var engine = this._scene.getEngine();
  78108. // Indices
  78109. var indices = [];
  78110. indices.push(0);
  78111. indices.push(1);
  78112. indices.push(2);
  78113. indices.push(0);
  78114. indices.push(2);
  78115. indices.push(3);
  78116. this._indexBuffer = engine.createIndexBuffer(indices);
  78117. };
  78118. Layer.prototype._rebuild = function () {
  78119. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78120. if (vb) {
  78121. vb._rebuild();
  78122. }
  78123. this._createIndexBuffer();
  78124. };
  78125. Layer.prototype.render = function () {
  78126. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78127. // Check
  78128. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78129. return;
  78130. var engine = this._scene.getEngine();
  78131. this.onBeforeRenderObservable.notifyObservers(this);
  78132. // Render
  78133. engine.enableEffect(currentEffect);
  78134. engine.setState(false);
  78135. // Texture
  78136. currentEffect.setTexture("textureSampler", this.texture);
  78137. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78138. // Color
  78139. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78140. // Scale / offset
  78141. currentEffect.setVector2("offset", this.offset);
  78142. currentEffect.setVector2("scale", this.scale);
  78143. // VBOs
  78144. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78145. // Draw order
  78146. if (!this.alphaTest) {
  78147. engine.setAlphaMode(this.alphaBlendingMode);
  78148. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78149. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78150. }
  78151. else {
  78152. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78153. }
  78154. this.onAfterRenderObservable.notifyObservers(this);
  78155. };
  78156. Layer.prototype.dispose = function () {
  78157. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78158. if (vertexBuffer) {
  78159. vertexBuffer.dispose();
  78160. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78161. }
  78162. if (this._indexBuffer) {
  78163. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78164. this._indexBuffer = null;
  78165. }
  78166. if (this.texture) {
  78167. this.texture.dispose();
  78168. this.texture = null;
  78169. }
  78170. // Remove from scene
  78171. var index = this._scene.layers.indexOf(this);
  78172. this._scene.layers.splice(index, 1);
  78173. // Callback
  78174. this.onDisposeObservable.notifyObservers(this);
  78175. this.onDisposeObservable.clear();
  78176. this.onAfterRenderObservable.clear();
  78177. this.onBeforeRenderObservable.clear();
  78178. };
  78179. return Layer;
  78180. }());
  78181. BABYLON.Layer = Layer;
  78182. })(BABYLON || (BABYLON = {}));
  78183. //# sourceMappingURL=babylon.layer.js.map
  78184. var BABYLON;
  78185. (function (BABYLON) {
  78186. var TextureTools = /** @class */ (function () {
  78187. function TextureTools() {
  78188. }
  78189. /**
  78190. * Uses the GPU to create a copy texture rescaled at a given size
  78191. * @param texture Texture to copy from
  78192. * @param width Desired width
  78193. * @param height Desired height
  78194. * @return Generated texture
  78195. */
  78196. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78197. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78198. var scene = texture.getScene();
  78199. var engine = scene.getEngine();
  78200. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78201. rtt.wrapU = texture.wrapU;
  78202. rtt.wrapV = texture.wrapV;
  78203. rtt.uOffset = texture.uOffset;
  78204. rtt.vOffset = texture.vOffset;
  78205. rtt.uScale = texture.uScale;
  78206. rtt.vScale = texture.vScale;
  78207. rtt.uAng = texture.uAng;
  78208. rtt.vAng = texture.vAng;
  78209. rtt.wAng = texture.wAng;
  78210. rtt.coordinatesIndex = texture.coordinatesIndex;
  78211. rtt.level = texture.level;
  78212. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78213. rtt._texture.isReady = false;
  78214. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78215. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78216. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78217. passPostProcess.getEffect().executeWhenCompiled(function () {
  78218. passPostProcess.onApply = function (effect) {
  78219. effect.setTexture("textureSampler", texture);
  78220. };
  78221. var internalTexture = rtt.getInternalTexture();
  78222. if (internalTexture) {
  78223. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78224. engine.unBindFramebuffer(internalTexture);
  78225. rtt.disposeFramebufferObjects();
  78226. passPostProcess.dispose();
  78227. internalTexture.isReady = true;
  78228. }
  78229. });
  78230. return rtt;
  78231. };
  78232. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78233. if (!scene._environmentBRDFTexture) {
  78234. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78235. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78236. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78237. scene._environmentBRDFTexture = texture;
  78238. }
  78239. return scene._environmentBRDFTexture;
  78240. };
  78241. 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=";
  78242. return TextureTools;
  78243. }());
  78244. BABYLON.TextureTools = TextureTools;
  78245. })(BABYLON || (BABYLON = {}));
  78246. //# sourceMappingURL=babylon.textureTools.js.map
  78247. var BABYLON;
  78248. (function (BABYLON) {
  78249. var FramingBehavior = /** @class */ (function () {
  78250. function FramingBehavior() {
  78251. this._mode = FramingBehavior.FitFrustumSidesMode;
  78252. this._radiusScale = 1.0;
  78253. this._positionScale = 0.5;
  78254. this._defaultElevation = 0.3;
  78255. this._elevationReturnTime = 1500;
  78256. this._elevationReturnWaitTime = 1000;
  78257. this._zoomStopsAnimation = false;
  78258. this._framingTime = 1500;
  78259. this._isPointerDown = false;
  78260. this._lastInteractionTime = -Infinity;
  78261. // Framing control
  78262. this._animatables = new Array();
  78263. this._betaIsAnimating = false;
  78264. }
  78265. Object.defineProperty(FramingBehavior.prototype, "name", {
  78266. get: function () {
  78267. return "Framing";
  78268. },
  78269. enumerable: true,
  78270. configurable: true
  78271. });
  78272. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78273. /**
  78274. * Gets current mode used by the behavior.
  78275. */
  78276. get: function () {
  78277. return this._mode;
  78278. },
  78279. /**
  78280. * Sets the current mode used by the behavior
  78281. */
  78282. set: function (mode) {
  78283. this._mode = mode;
  78284. },
  78285. enumerable: true,
  78286. configurable: true
  78287. });
  78288. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78289. /**
  78290. * Gets the scale applied to the radius
  78291. */
  78292. get: function () {
  78293. return this._radiusScale;
  78294. },
  78295. /**
  78296. * Sets the scale applied to the radius (1 by default)
  78297. */
  78298. set: function (radius) {
  78299. this._radiusScale = radius;
  78300. },
  78301. enumerable: true,
  78302. configurable: true
  78303. });
  78304. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78305. /**
  78306. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78307. */
  78308. get: function () {
  78309. return this._positionScale;
  78310. },
  78311. /**
  78312. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78313. */
  78314. set: function (scale) {
  78315. this._positionScale = scale;
  78316. },
  78317. enumerable: true,
  78318. configurable: true
  78319. });
  78320. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78321. /**
  78322. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78323. * behaviour is triggered, in radians.
  78324. */
  78325. get: function () {
  78326. return this._defaultElevation;
  78327. },
  78328. /**
  78329. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78330. * behaviour is triggered, in radians.
  78331. */
  78332. set: function (elevation) {
  78333. this._defaultElevation = elevation;
  78334. },
  78335. enumerable: true,
  78336. configurable: true
  78337. });
  78338. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78339. /**
  78340. * Gets the time (in milliseconds) taken to return to the default beta position.
  78341. * Negative value indicates camera should not return to default.
  78342. */
  78343. get: function () {
  78344. return this._elevationReturnTime;
  78345. },
  78346. /**
  78347. * Sets the time (in milliseconds) taken to return to the default beta position.
  78348. * Negative value indicates camera should not return to default.
  78349. */
  78350. set: function (speed) {
  78351. this._elevationReturnTime = speed;
  78352. },
  78353. enumerable: true,
  78354. configurable: true
  78355. });
  78356. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78357. /**
  78358. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78359. */
  78360. get: function () {
  78361. return this._elevationReturnWaitTime;
  78362. },
  78363. /**
  78364. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78365. */
  78366. set: function (time) {
  78367. this._elevationReturnWaitTime = time;
  78368. },
  78369. enumerable: true,
  78370. configurable: true
  78371. });
  78372. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  78373. /**
  78374. * Gets the flag that indicates if user zooming should stop animation.
  78375. */
  78376. get: function () {
  78377. return this._zoomStopsAnimation;
  78378. },
  78379. /**
  78380. * Sets the flag that indicates if user zooming should stop animation.
  78381. */
  78382. set: function (flag) {
  78383. this._zoomStopsAnimation = flag;
  78384. },
  78385. enumerable: true,
  78386. configurable: true
  78387. });
  78388. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  78389. /**
  78390. * Gets the transition time when framing the mesh, in milliseconds
  78391. */
  78392. get: function () {
  78393. return this._framingTime;
  78394. },
  78395. /**
  78396. * Sets the transition time when framing the mesh, in milliseconds
  78397. */
  78398. set: function (time) {
  78399. this._framingTime = time;
  78400. },
  78401. enumerable: true,
  78402. configurable: true
  78403. });
  78404. FramingBehavior.prototype.init = function () {
  78405. // Do notihng
  78406. };
  78407. FramingBehavior.prototype.attach = function (camera) {
  78408. var _this = this;
  78409. this._attachedCamera = camera;
  78410. var scene = this._attachedCamera.getScene();
  78411. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  78412. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78413. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78414. _this._isPointerDown = true;
  78415. return;
  78416. }
  78417. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78418. _this._isPointerDown = false;
  78419. }
  78420. });
  78421. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78422. if (mesh) {
  78423. _this.zoomOnMesh(mesh);
  78424. }
  78425. });
  78426. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78427. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78428. _this._applyUserInteraction();
  78429. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  78430. // back to the default position after a given timeout
  78431. _this._maintainCameraAboveGround();
  78432. });
  78433. };
  78434. FramingBehavior.prototype.detach = function () {
  78435. if (!this._attachedCamera) {
  78436. return;
  78437. }
  78438. var scene = this._attachedCamera.getScene();
  78439. if (this._onPrePointerObservableObserver) {
  78440. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78441. }
  78442. if (this._onAfterCheckInputsObserver) {
  78443. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78444. }
  78445. if (this._onMeshTargetChangedObserver) {
  78446. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78447. }
  78448. this._attachedCamera = null;
  78449. };
  78450. /**
  78451. * Targets the given mesh and updates zoom level accordingly.
  78452. * @param mesh The mesh to target.
  78453. * @param radius Optional. If a cached radius position already exists, overrides default.
  78454. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78455. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78456. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78457. */
  78458. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78459. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78460. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78461. mesh.computeWorldMatrix(true);
  78462. var boundingBox = mesh.getBoundingInfo().boundingBox;
  78463. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  78464. };
  78465. /**
  78466. * Targets the given mesh with its children and updates zoom level accordingly.
  78467. * @param mesh The mesh to target.
  78468. * @param radius Optional. If a cached radius position already exists, overrides default.
  78469. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78470. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78471. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78472. */
  78473. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78474. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78475. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78476. mesh.computeWorldMatrix(true);
  78477. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  78478. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  78479. };
  78480. /**
  78481. * Targets the given meshes with their children and updates zoom level accordingly.
  78482. * @param meshes The mesh to target.
  78483. * @param radius Optional. If a cached radius position already exists, overrides default.
  78484. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78485. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78486. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78487. */
  78488. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  78489. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78490. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78491. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  78492. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  78493. for (var i = 0; i < meshes.length; i++) {
  78494. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  78495. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  78496. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  78497. }
  78498. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  78499. };
  78500. /**
  78501. * Targets the given mesh and updates zoom level accordingly.
  78502. * @param mesh The mesh to target.
  78503. * @param radius Optional. If a cached radius position already exists, overrides default.
  78504. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78505. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78506. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78507. */
  78508. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  78509. var _this = this;
  78510. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78511. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78512. var zoomTarget;
  78513. if (!this._attachedCamera) {
  78514. return;
  78515. }
  78516. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  78517. var bottom = minimumWorld.y;
  78518. var top = maximumWorld.y;
  78519. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  78520. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  78521. if (focusOnOriginXZ) {
  78522. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  78523. }
  78524. else {
  78525. var centerWorld = minimumWorld.add(radiusWorld);
  78526. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  78527. }
  78528. if (!this._vectorTransition) {
  78529. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  78530. }
  78531. this._betaIsAnimating = true;
  78532. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  78533. if (animatable) {
  78534. this._animatables.push(animatable);
  78535. }
  78536. // sets the radius and lower radius bounds
  78537. // Small delta ensures camera is not always at lower zoom limit.
  78538. var radius = 0;
  78539. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  78540. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78541. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  78542. radius = position;
  78543. }
  78544. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78545. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78546. if (this._attachedCamera.lowerRadiusLimit === null) {
  78547. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  78548. }
  78549. }
  78550. // Set sensibilities
  78551. var extend = maximumWorld.subtract(minimumWorld).length();
  78552. this._attachedCamera.panningSensibility = 5000 / extend;
  78553. this._attachedCamera.wheelPrecision = 100 / radius;
  78554. // transition to new radius
  78555. if (!this._radiusTransition) {
  78556. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78557. }
  78558. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  78559. if (onAnimationEnd) {
  78560. onAnimationEnd();
  78561. }
  78562. if (_this._attachedCamera) {
  78563. _this._attachedCamera.storeState();
  78564. }
  78565. });
  78566. if (animatable) {
  78567. this._animatables.push(animatable);
  78568. }
  78569. };
  78570. /**
  78571. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  78572. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  78573. * frustum width.
  78574. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  78575. * to fully enclose the mesh in the viewing frustum.
  78576. */
  78577. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  78578. var size = maximumWorld.subtract(minimumWorld);
  78579. var boxVectorGlobalDiagonal = size.length();
  78580. var frustumSlope = this._getFrustumSlope();
  78581. // Formula for setting distance
  78582. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  78583. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  78584. // Horizon distance
  78585. var radius = radiusWithoutFraming * this._radiusScale;
  78586. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  78587. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  78588. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  78589. var camera = this._attachedCamera;
  78590. if (!camera) {
  78591. return 0;
  78592. }
  78593. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78594. // Don't exceed the requested limit
  78595. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  78596. }
  78597. // Don't exceed the upper radius limit
  78598. if (camera.upperRadiusLimit) {
  78599. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  78600. }
  78601. return distance;
  78602. };
  78603. /**
  78604. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  78605. * is automatically returned to its default position (expected to be above ground plane).
  78606. */
  78607. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  78608. var _this = this;
  78609. if (this._elevationReturnTime < 0) {
  78610. return;
  78611. }
  78612. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  78613. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  78614. var limitBeta = Math.PI * 0.5;
  78615. // Bring the camera back up if below the ground plane
  78616. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  78617. this._betaIsAnimating = true;
  78618. //Transition to new position
  78619. this.stopAllAnimations();
  78620. if (!this._betaTransition) {
  78621. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78622. }
  78623. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  78624. _this._clearAnimationLocks();
  78625. _this.stopAllAnimations();
  78626. });
  78627. if (animatabe) {
  78628. this._animatables.push(animatabe);
  78629. }
  78630. }
  78631. };
  78632. /**
  78633. * Returns the frustum slope based on the canvas ratio and camera FOV
  78634. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  78635. */
  78636. FramingBehavior.prototype._getFrustumSlope = function () {
  78637. // Calculate the viewport ratio
  78638. // Aspect Ratio is Height/Width.
  78639. var camera = this._attachedCamera;
  78640. if (!camera) {
  78641. return BABYLON.Vector2.Zero();
  78642. }
  78643. var engine = camera.getScene().getEngine();
  78644. var aspectRatio = engine.getAspectRatio(camera);
  78645. // Camera FOV is the vertical field of view (top-bottom) in radians.
  78646. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  78647. var frustumSlopeY = Math.tan(camera.fov / 2);
  78648. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  78649. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  78650. // along the forward vector.
  78651. var frustumSlopeX = frustumSlopeY * aspectRatio;
  78652. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  78653. };
  78654. /**
  78655. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  78656. */
  78657. FramingBehavior.prototype._clearAnimationLocks = function () {
  78658. this._betaIsAnimating = false;
  78659. };
  78660. /**
  78661. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  78662. */
  78663. FramingBehavior.prototype._applyUserInteraction = function () {
  78664. if (this.isUserIsMoving) {
  78665. this._lastInteractionTime = BABYLON.Tools.Now;
  78666. this.stopAllAnimations();
  78667. this._clearAnimationLocks();
  78668. }
  78669. };
  78670. /**
  78671. * Stops and removes all animations that have been applied to the camera
  78672. */
  78673. FramingBehavior.prototype.stopAllAnimations = function () {
  78674. if (this._attachedCamera) {
  78675. this._attachedCamera.animations = [];
  78676. }
  78677. while (this._animatables.length) {
  78678. if (this._animatables[0]) {
  78679. this._animatables[0].onAnimationEnd = null;
  78680. this._animatables[0].stop();
  78681. }
  78682. this._animatables.shift();
  78683. }
  78684. };
  78685. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  78686. /**
  78687. * Gets a value indicating if the user is moving the camera
  78688. */
  78689. get: function () {
  78690. if (!this._attachedCamera) {
  78691. return false;
  78692. }
  78693. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  78694. this._attachedCamera.inertialBetaOffset !== 0 ||
  78695. this._attachedCamera.inertialRadiusOffset !== 0 ||
  78696. this._attachedCamera.inertialPanningX !== 0 ||
  78697. this._attachedCamera.inertialPanningY !== 0 ||
  78698. this._isPointerDown;
  78699. },
  78700. enumerable: true,
  78701. configurable: true
  78702. });
  78703. /**
  78704. * The easing function used by animations
  78705. */
  78706. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  78707. /**
  78708. * The easing mode used by animations
  78709. */
  78710. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  78711. // Statics
  78712. /**
  78713. * The camera can move all the way towards the mesh.
  78714. */
  78715. FramingBehavior.IgnoreBoundsSizeMode = 0;
  78716. /**
  78717. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  78718. */
  78719. FramingBehavior.FitFrustumSidesMode = 1;
  78720. return FramingBehavior;
  78721. }());
  78722. BABYLON.FramingBehavior = FramingBehavior;
  78723. })(BABYLON || (BABYLON = {}));
  78724. //# sourceMappingURL=babylon.framingBehavior.js.map
  78725. var BABYLON;
  78726. (function (BABYLON) {
  78727. /**
  78728. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  78729. */
  78730. var BouncingBehavior = /** @class */ (function () {
  78731. function BouncingBehavior() {
  78732. /**
  78733. * The duration of the animation, in milliseconds
  78734. */
  78735. this.transitionDuration = 450;
  78736. /**
  78737. * Length of the distance animated by the transition when lower radius is reached
  78738. */
  78739. this.lowerRadiusTransitionRange = 2;
  78740. /**
  78741. * Length of the distance animated by the transition when upper radius is reached
  78742. */
  78743. this.upperRadiusTransitionRange = -2;
  78744. this._autoTransitionRange = false;
  78745. // Animations
  78746. this._radiusIsAnimating = false;
  78747. this._radiusBounceTransition = null;
  78748. this._animatables = new Array();
  78749. }
  78750. Object.defineProperty(BouncingBehavior.prototype, "name", {
  78751. get: function () {
  78752. return "Bouncing";
  78753. },
  78754. enumerable: true,
  78755. configurable: true
  78756. });
  78757. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  78758. /**
  78759. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  78760. */
  78761. get: function () {
  78762. return this._autoTransitionRange;
  78763. },
  78764. /**
  78765. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  78766. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  78767. */
  78768. set: function (value) {
  78769. var _this = this;
  78770. if (this._autoTransitionRange === value) {
  78771. return;
  78772. }
  78773. this._autoTransitionRange = value;
  78774. var camera = this._attachedCamera;
  78775. if (!camera) {
  78776. return;
  78777. }
  78778. if (value) {
  78779. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78780. if (!mesh) {
  78781. return;
  78782. }
  78783. mesh.computeWorldMatrix(true);
  78784. var diagonal = mesh.getBoundingInfo().diagonalLength;
  78785. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  78786. _this.upperRadiusTransitionRange = diagonal * 0.05;
  78787. });
  78788. }
  78789. else if (this._onMeshTargetChangedObserver) {
  78790. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78791. }
  78792. },
  78793. enumerable: true,
  78794. configurable: true
  78795. });
  78796. BouncingBehavior.prototype.init = function () {
  78797. // Do notihng
  78798. };
  78799. BouncingBehavior.prototype.attach = function (camera) {
  78800. var _this = this;
  78801. this._attachedCamera = camera;
  78802. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78803. if (!_this._attachedCamera) {
  78804. return;
  78805. }
  78806. // Add the bounce animation to the lower radius limit
  78807. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  78808. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  78809. }
  78810. // Add the bounce animation to the upper radius limit
  78811. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  78812. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  78813. }
  78814. });
  78815. };
  78816. BouncingBehavior.prototype.detach = function () {
  78817. if (!this._attachedCamera) {
  78818. return;
  78819. }
  78820. if (this._onAfterCheckInputsObserver) {
  78821. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78822. }
  78823. if (this._onMeshTargetChangedObserver) {
  78824. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78825. }
  78826. this._attachedCamera = null;
  78827. };
  78828. /**
  78829. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  78830. * @param radiusLimit The limit to check against.
  78831. * @return Bool to indicate if at limit.
  78832. */
  78833. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  78834. if (!this._attachedCamera) {
  78835. return false;
  78836. }
  78837. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  78838. return true;
  78839. }
  78840. return false;
  78841. };
  78842. /**
  78843. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  78844. * @param radiusDelta The delta by which to animate to. Can be negative.
  78845. */
  78846. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  78847. var _this = this;
  78848. if (!this._attachedCamera) {
  78849. return;
  78850. }
  78851. if (!this._radiusBounceTransition) {
  78852. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  78853. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  78854. }
  78855. // Prevent zoom until bounce has completed
  78856. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  78857. this._attachedCamera.wheelPrecision = Infinity;
  78858. this._attachedCamera.inertialRadiusOffset = 0;
  78859. // Animate to the radius limit
  78860. this.stopAllAnimations();
  78861. this._radiusIsAnimating = true;
  78862. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  78863. if (animatable) {
  78864. this._animatables.push(animatable);
  78865. }
  78866. };
  78867. /**
  78868. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  78869. */
  78870. BouncingBehavior.prototype._clearAnimationLocks = function () {
  78871. this._radiusIsAnimating = false;
  78872. if (this._attachedCamera) {
  78873. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  78874. }
  78875. };
  78876. /**
  78877. * Stops and removes all animations that have been applied to the camera
  78878. */
  78879. BouncingBehavior.prototype.stopAllAnimations = function () {
  78880. if (this._attachedCamera) {
  78881. this._attachedCamera.animations = [];
  78882. }
  78883. while (this._animatables.length) {
  78884. this._animatables[0].onAnimationEnd = null;
  78885. this._animatables[0].stop();
  78886. this._animatables.shift();
  78887. }
  78888. };
  78889. /**
  78890. * The easing function used by animations
  78891. */
  78892. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  78893. /**
  78894. * The easing mode used by animations
  78895. */
  78896. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  78897. return BouncingBehavior;
  78898. }());
  78899. BABYLON.BouncingBehavior = BouncingBehavior;
  78900. })(BABYLON || (BABYLON = {}));
  78901. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  78902. var BABYLON;
  78903. (function (BABYLON) {
  78904. var AutoRotationBehavior = /** @class */ (function () {
  78905. function AutoRotationBehavior() {
  78906. this._zoomStopsAnimation = false;
  78907. this._idleRotationSpeed = 0.05;
  78908. this._idleRotationWaitTime = 2000;
  78909. this._idleRotationSpinupTime = 2000;
  78910. this._isPointerDown = false;
  78911. this._lastFrameTime = null;
  78912. this._lastInteractionTime = -Infinity;
  78913. this._cameraRotationSpeed = 0;
  78914. this._lastFrameRadius = 0;
  78915. }
  78916. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  78917. get: function () {
  78918. return "AutoRotation";
  78919. },
  78920. enumerable: true,
  78921. configurable: true
  78922. });
  78923. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  78924. /**
  78925. * Gets the flag that indicates if user zooming should stop animation.
  78926. */
  78927. get: function () {
  78928. return this._zoomStopsAnimation;
  78929. },
  78930. /**
  78931. * Sets the flag that indicates if user zooming should stop animation.
  78932. */
  78933. set: function (flag) {
  78934. this._zoomStopsAnimation = flag;
  78935. },
  78936. enumerable: true,
  78937. configurable: true
  78938. });
  78939. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  78940. /**
  78941. * Gets the default speed at which the camera rotates around the model.
  78942. */
  78943. get: function () {
  78944. return this._idleRotationSpeed;
  78945. },
  78946. /**
  78947. * Sets the default speed at which the camera rotates around the model.
  78948. */
  78949. set: function (speed) {
  78950. this._idleRotationSpeed = speed;
  78951. },
  78952. enumerable: true,
  78953. configurable: true
  78954. });
  78955. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  78956. /**
  78957. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  78958. */
  78959. get: function () {
  78960. return this._idleRotationWaitTime;
  78961. },
  78962. /**
  78963. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  78964. */
  78965. set: function (time) {
  78966. this._idleRotationWaitTime = time;
  78967. },
  78968. enumerable: true,
  78969. configurable: true
  78970. });
  78971. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  78972. /**
  78973. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  78974. */
  78975. get: function () {
  78976. return this._idleRotationSpinupTime;
  78977. },
  78978. /**
  78979. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  78980. */
  78981. set: function (time) {
  78982. this._idleRotationSpinupTime = time;
  78983. },
  78984. enumerable: true,
  78985. configurable: true
  78986. });
  78987. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  78988. /**
  78989. * Gets a value indicating if the camera is currently rotating because of this behavior
  78990. */
  78991. get: function () {
  78992. return Math.abs(this._cameraRotationSpeed) > 0;
  78993. },
  78994. enumerable: true,
  78995. configurable: true
  78996. });
  78997. AutoRotationBehavior.prototype.init = function () {
  78998. // Do notihng
  78999. };
  79000. AutoRotationBehavior.prototype.attach = function (camera) {
  79001. var _this = this;
  79002. this._attachedCamera = camera;
  79003. var scene = this._attachedCamera.getScene();
  79004. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79005. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79006. _this._isPointerDown = true;
  79007. return;
  79008. }
  79009. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79010. _this._isPointerDown = false;
  79011. }
  79012. });
  79013. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79014. var now = BABYLON.Tools.Now;
  79015. var dt = 0;
  79016. if (_this._lastFrameTime != null) {
  79017. dt = now - _this._lastFrameTime;
  79018. }
  79019. _this._lastFrameTime = now;
  79020. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79021. _this._applyUserInteraction();
  79022. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79023. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79024. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79025. // Step camera rotation by rotation speed
  79026. if (_this._attachedCamera) {
  79027. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79028. }
  79029. });
  79030. };
  79031. AutoRotationBehavior.prototype.detach = function () {
  79032. if (!this._attachedCamera) {
  79033. return;
  79034. }
  79035. var scene = this._attachedCamera.getScene();
  79036. if (this._onPrePointerObservableObserver) {
  79037. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79038. }
  79039. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79040. this._attachedCamera = null;
  79041. };
  79042. /**
  79043. * Returns true if user is scrolling.
  79044. * @return true if user is scrolling.
  79045. */
  79046. AutoRotationBehavior.prototype._userIsZooming = function () {
  79047. if (!this._attachedCamera) {
  79048. return false;
  79049. }
  79050. return this._attachedCamera.inertialRadiusOffset !== 0;
  79051. };
  79052. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79053. if (!this._attachedCamera) {
  79054. return false;
  79055. }
  79056. var zoomHasHitLimit = false;
  79057. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79058. zoomHasHitLimit = true;
  79059. }
  79060. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79061. this._lastFrameRadius = this._attachedCamera.radius;
  79062. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79063. };
  79064. /**
  79065. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79066. */
  79067. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79068. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79069. this._lastInteractionTime = BABYLON.Tools.Now;
  79070. }
  79071. };
  79072. // Tools
  79073. AutoRotationBehavior.prototype._userIsMoving = function () {
  79074. if (!this._attachedCamera) {
  79075. return false;
  79076. }
  79077. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79078. this._attachedCamera.inertialBetaOffset !== 0 ||
  79079. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79080. this._attachedCamera.inertialPanningX !== 0 ||
  79081. this._attachedCamera.inertialPanningY !== 0 ||
  79082. this._isPointerDown;
  79083. };
  79084. return AutoRotationBehavior;
  79085. }());
  79086. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79087. })(BABYLON || (BABYLON = {}));
  79088. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79089. var BABYLON;
  79090. (function (BABYLON) {
  79091. var NullEngineOptions = /** @class */ (function () {
  79092. function NullEngineOptions() {
  79093. this.renderWidth = 512;
  79094. this.renderHeight = 256;
  79095. this.textureSize = 512;
  79096. this.deterministicLockstep = false;
  79097. this.lockstepMaxSteps = 4;
  79098. }
  79099. return NullEngineOptions;
  79100. }());
  79101. BABYLON.NullEngineOptions = NullEngineOptions;
  79102. /**
  79103. * The null engine class provides support for headless version of babylon.js.
  79104. * This can be used in server side scenario or for testing purposes
  79105. */
  79106. var NullEngine = /** @class */ (function (_super) {
  79107. __extends(NullEngine, _super);
  79108. function NullEngine(options) {
  79109. if (options === void 0) { options = new NullEngineOptions(); }
  79110. var _this = _super.call(this, null) || this;
  79111. if (options.deterministicLockstep === undefined) {
  79112. options.deterministicLockstep = false;
  79113. }
  79114. if (options.lockstepMaxSteps === undefined) {
  79115. options.lockstepMaxSteps = 4;
  79116. }
  79117. _this._options = options;
  79118. // Init caps
  79119. // We consider we are on a webgl1 capable device
  79120. _this._caps = new BABYLON.EngineCapabilities();
  79121. _this._caps.maxTexturesImageUnits = 16;
  79122. _this._caps.maxVertexTextureImageUnits = 16;
  79123. _this._caps.maxTextureSize = 512;
  79124. _this._caps.maxCubemapTextureSize = 512;
  79125. _this._caps.maxRenderTextureSize = 512;
  79126. _this._caps.maxVertexAttribs = 16;
  79127. _this._caps.maxVaryingVectors = 16;
  79128. _this._caps.maxFragmentUniformVectors = 16;
  79129. _this._caps.maxVertexUniformVectors = 16;
  79130. // Extensions
  79131. _this._caps.standardDerivatives = false;
  79132. _this._caps.astc = null;
  79133. _this._caps.s3tc = null;
  79134. _this._caps.pvrtc = null;
  79135. _this._caps.etc1 = null;
  79136. _this._caps.etc2 = null;
  79137. _this._caps.textureAnisotropicFilterExtension = null;
  79138. _this._caps.maxAnisotropy = 0;
  79139. _this._caps.uintIndices = false;
  79140. _this._caps.fragmentDepthSupported = false;
  79141. _this._caps.highPrecisionShaderSupported = true;
  79142. _this._caps.colorBufferFloat = false;
  79143. _this._caps.textureFloat = false;
  79144. _this._caps.textureFloatLinearFiltering = false;
  79145. _this._caps.textureFloatRender = false;
  79146. _this._caps.textureHalfFloat = false;
  79147. _this._caps.textureHalfFloatLinearFiltering = false;
  79148. _this._caps.textureHalfFloatRender = false;
  79149. _this._caps.textureLOD = false;
  79150. _this._caps.drawBuffersExtension = false;
  79151. _this._caps.depthTextureExtension = false;
  79152. _this._caps.vertexArrayObject = false;
  79153. _this._caps.instancedArrays = false;
  79154. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  79155. // Wrappers
  79156. if (typeof URL === "undefined") {
  79157. URL = {
  79158. createObjectURL: function () { },
  79159. revokeObjectURL: function () { }
  79160. };
  79161. }
  79162. if (typeof Blob === "undefined") {
  79163. Blob = function () { };
  79164. }
  79165. return _this;
  79166. }
  79167. NullEngine.prototype.isDeterministicLockStep = function () {
  79168. return this._options.deterministicLockstep;
  79169. };
  79170. NullEngine.prototype.getLockstepMaxSteps = function () {
  79171. return this._options.lockstepMaxSteps;
  79172. };
  79173. NullEngine.prototype.createVertexBuffer = function (vertices) {
  79174. return {
  79175. capacity: 0,
  79176. references: 1,
  79177. is32Bits: false
  79178. };
  79179. };
  79180. NullEngine.prototype.createIndexBuffer = function (indices) {
  79181. return {
  79182. capacity: 0,
  79183. references: 1,
  79184. is32Bits: false
  79185. };
  79186. };
  79187. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  79188. if (stencil === void 0) { stencil = false; }
  79189. };
  79190. NullEngine.prototype.getRenderWidth = function (useScreen) {
  79191. if (useScreen === void 0) { useScreen = false; }
  79192. if (!useScreen && this._currentRenderTarget) {
  79193. return this._currentRenderTarget.width;
  79194. }
  79195. return this._options.renderWidth;
  79196. };
  79197. NullEngine.prototype.getRenderHeight = function (useScreen) {
  79198. if (useScreen === void 0) { useScreen = false; }
  79199. if (!useScreen && this._currentRenderTarget) {
  79200. return this._currentRenderTarget.height;
  79201. }
  79202. return this._options.renderHeight;
  79203. };
  79204. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  79205. this._cachedViewport = viewport;
  79206. };
  79207. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  79208. return {
  79209. transformFeedback: null,
  79210. __SPECTOR_rebuildProgram: null
  79211. };
  79212. };
  79213. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  79214. return [];
  79215. };
  79216. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  79217. return [];
  79218. };
  79219. NullEngine.prototype.bindSamplers = function (effect) {
  79220. this._currentEffect = null;
  79221. };
  79222. NullEngine.prototype.enableEffect = function (effect) {
  79223. this._currentEffect = effect;
  79224. if (effect.onBind) {
  79225. effect.onBind(effect);
  79226. }
  79227. effect.onBindObservable.notifyObservers(effect);
  79228. };
  79229. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  79230. if (zOffset === void 0) { zOffset = 0; }
  79231. if (reverseSide === void 0) { reverseSide = false; }
  79232. };
  79233. NullEngine.prototype.setIntArray = function (uniform, array) {
  79234. };
  79235. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  79236. };
  79237. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  79238. };
  79239. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  79240. };
  79241. NullEngine.prototype.setFloatArray = function (uniform, array) {
  79242. };
  79243. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  79244. };
  79245. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  79246. };
  79247. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  79248. };
  79249. NullEngine.prototype.setArray = function (uniform, array) {
  79250. };
  79251. NullEngine.prototype.setArray2 = function (uniform, array) {
  79252. };
  79253. NullEngine.prototype.setArray3 = function (uniform, array) {
  79254. };
  79255. NullEngine.prototype.setArray4 = function (uniform, array) {
  79256. };
  79257. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  79258. };
  79259. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  79260. };
  79261. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  79262. };
  79263. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  79264. };
  79265. NullEngine.prototype.setFloat = function (uniform, value) {
  79266. };
  79267. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  79268. };
  79269. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  79270. };
  79271. NullEngine.prototype.setBool = function (uniform, bool) {
  79272. };
  79273. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  79274. };
  79275. NullEngine.prototype.setColor3 = function (uniform, color3) {
  79276. };
  79277. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  79278. };
  79279. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  79280. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  79281. if (this._alphaMode === mode) {
  79282. return;
  79283. }
  79284. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  79285. if (!noDepthWriteChange) {
  79286. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  79287. }
  79288. this._alphaMode = mode;
  79289. };
  79290. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  79291. };
  79292. NullEngine.prototype.wipeCaches = function (bruteForce) {
  79293. if (this.preventCacheWipeBetweenFrames) {
  79294. return;
  79295. }
  79296. this.resetTextureCache();
  79297. this._currentEffect = null;
  79298. if (bruteForce) {
  79299. this._currentProgram = null;
  79300. this._stencilState.reset();
  79301. this._depthCullingState.reset();
  79302. this.setDepthFunctionToLessOrEqual();
  79303. this._alphaState.reset();
  79304. }
  79305. this._cachedVertexBuffers = null;
  79306. this._cachedIndexBuffer = null;
  79307. this._cachedEffectForVertexBuffers = null;
  79308. };
  79309. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  79310. };
  79311. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  79312. };
  79313. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  79314. };
  79315. NullEngine.prototype._createTexture = function () {
  79316. return {};
  79317. };
  79318. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  79319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79320. if (onLoad === void 0) { onLoad = null; }
  79321. if (onError === void 0) { onError = null; }
  79322. if (buffer === void 0) { buffer = null; }
  79323. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  79324. var url = String(urlArg);
  79325. texture.url = url;
  79326. texture.generateMipMaps = !noMipmap;
  79327. texture.samplingMode = samplingMode;
  79328. texture.invertY = invertY;
  79329. texture.baseWidth = this._options.textureSize;
  79330. texture.baseHeight = this._options.textureSize;
  79331. texture.width = this._options.textureSize;
  79332. texture.height = this._options.textureSize;
  79333. if (format) {
  79334. texture.format = format;
  79335. }
  79336. texture.isReady = true;
  79337. if (onLoad) {
  79338. onLoad();
  79339. }
  79340. return texture;
  79341. };
  79342. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  79343. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  79344. if (options !== undefined && typeof options === "object") {
  79345. fullOptions.generateMipMaps = options.generateMipMaps;
  79346. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  79347. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  79348. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  79349. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  79350. }
  79351. else {
  79352. fullOptions.generateMipMaps = options;
  79353. fullOptions.generateDepthBuffer = true;
  79354. fullOptions.generateStencilBuffer = false;
  79355. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79356. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  79357. }
  79358. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  79359. var width = size.width || size;
  79360. var height = size.height || size;
  79361. texture._depthStencilBuffer = {};
  79362. texture._framebuffer = {};
  79363. texture.baseWidth = width;
  79364. texture.baseHeight = height;
  79365. texture.width = width;
  79366. texture.height = height;
  79367. texture.isReady = true;
  79368. texture.samples = 1;
  79369. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  79370. texture.samplingMode = fullOptions.samplingMode;
  79371. texture.type = fullOptions.type;
  79372. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  79373. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  79374. return texture;
  79375. };
  79376. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  79377. texture.samplingMode = samplingMode;
  79378. };
  79379. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  79380. if (this._currentRenderTarget) {
  79381. this.unBindFramebuffer(this._currentRenderTarget);
  79382. }
  79383. this._currentRenderTarget = texture;
  79384. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  79385. if (this._cachedViewport && !forceFullscreenViewport) {
  79386. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  79387. }
  79388. };
  79389. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  79390. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  79391. this._currentRenderTarget = null;
  79392. if (onBeforeUnbind) {
  79393. if (texture._MSAAFramebuffer) {
  79394. this._currentFramebuffer = texture._framebuffer;
  79395. }
  79396. onBeforeUnbind();
  79397. }
  79398. this._currentFramebuffer = null;
  79399. };
  79400. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  79401. var vbo = {
  79402. capacity: 1,
  79403. references: 1,
  79404. is32Bits: false
  79405. };
  79406. return vbo;
  79407. };
  79408. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  79409. if (offset === void 0) { offset = 0; }
  79410. };
  79411. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  79412. };
  79413. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  79414. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  79415. this._boundTexturesCache[this._activeChannel] = texture;
  79416. }
  79417. };
  79418. NullEngine.prototype._bindTexture = function (channel, texture) {
  79419. if (channel < 0) {
  79420. return;
  79421. }
  79422. this._bindTextureDirectly(0, texture);
  79423. };
  79424. NullEngine.prototype._releaseBuffer = function (buffer) {
  79425. buffer.references--;
  79426. if (buffer.references === 0) {
  79427. return true;
  79428. }
  79429. return false;
  79430. };
  79431. return NullEngine;
  79432. }(BABYLON.Engine));
  79433. BABYLON.NullEngine = NullEngine;
  79434. })(BABYLON || (BABYLON = {}));
  79435. //# sourceMappingURL=babylon.nullEngine.js.map
  79436. var BABYLON;
  79437. (function (BABYLON) {
  79438. /**
  79439. * This class can be used to get instrumentation data from a Babylon engine
  79440. */
  79441. var EngineInstrumentation = /** @class */ (function () {
  79442. function EngineInstrumentation(engine) {
  79443. this.engine = engine;
  79444. this._captureGPUFrameTime = false;
  79445. this._gpuFrameTime = new BABYLON.PerfCounter();
  79446. this._captureShaderCompilationTime = false;
  79447. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79448. // Observers
  79449. this._onBeginFrameObserver = null;
  79450. this._onEndFrameObserver = null;
  79451. this._onBeforeShaderCompilationObserver = null;
  79452. this._onAfterShaderCompilationObserver = null;
  79453. }
  79454. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79455. // Properties
  79456. /**
  79457. * Gets the perf counter used for GPU frame time
  79458. */
  79459. get: function () {
  79460. return this._gpuFrameTime;
  79461. },
  79462. enumerable: true,
  79463. configurable: true
  79464. });
  79465. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79466. /**
  79467. * Gets the GPU frame time capture status
  79468. */
  79469. get: function () {
  79470. return this._captureGPUFrameTime;
  79471. },
  79472. /**
  79473. * Enable or disable the GPU frame time capture
  79474. */
  79475. set: function (value) {
  79476. var _this = this;
  79477. if (value === this._captureGPUFrameTime) {
  79478. return;
  79479. }
  79480. this._captureGPUFrameTime = value;
  79481. if (value) {
  79482. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79483. if (!_this._gpuFrameTimeToken) {
  79484. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79485. }
  79486. });
  79487. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79488. if (!_this._gpuFrameTimeToken) {
  79489. return;
  79490. }
  79491. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79492. if (time > -1) {
  79493. _this._gpuFrameTimeToken = null;
  79494. _this._gpuFrameTime.fetchNewFrame();
  79495. _this._gpuFrameTime.addCount(time, true);
  79496. }
  79497. });
  79498. }
  79499. else {
  79500. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79501. this._onBeginFrameObserver = null;
  79502. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79503. this._onEndFrameObserver = null;
  79504. }
  79505. },
  79506. enumerable: true,
  79507. configurable: true
  79508. });
  79509. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79510. /**
  79511. * Gets the perf counter used for shader compilation time
  79512. */
  79513. get: function () {
  79514. return this._shaderCompilationTime;
  79515. },
  79516. enumerable: true,
  79517. configurable: true
  79518. });
  79519. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79520. /**
  79521. * Gets the shader compilation time capture status
  79522. */
  79523. get: function () {
  79524. return this._captureShaderCompilationTime;
  79525. },
  79526. /**
  79527. * Enable or disable the shader compilation time capture
  79528. */
  79529. set: function (value) {
  79530. var _this = this;
  79531. if (value === this._captureShaderCompilationTime) {
  79532. return;
  79533. }
  79534. this._captureShaderCompilationTime = value;
  79535. if (value) {
  79536. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79537. _this._shaderCompilationTime.fetchNewFrame();
  79538. _this._shaderCompilationTime.beginMonitoring();
  79539. });
  79540. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79541. _this._shaderCompilationTime.endMonitoring();
  79542. });
  79543. }
  79544. else {
  79545. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79546. this._onBeforeShaderCompilationObserver = null;
  79547. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79548. this._onAfterShaderCompilationObserver = null;
  79549. }
  79550. },
  79551. enumerable: true,
  79552. configurable: true
  79553. });
  79554. EngineInstrumentation.prototype.dispose = function () {
  79555. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79556. this._onBeginFrameObserver = null;
  79557. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79558. this._onEndFrameObserver = null;
  79559. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79560. this._onBeforeShaderCompilationObserver = null;
  79561. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79562. this._onAfterShaderCompilationObserver = null;
  79563. this.engine = null;
  79564. };
  79565. return EngineInstrumentation;
  79566. }());
  79567. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79568. })(BABYLON || (BABYLON = {}));
  79569. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79570. var BABYLON;
  79571. (function (BABYLON) {
  79572. /**
  79573. * This class can be used to get instrumentation data from a Babylon engine
  79574. */
  79575. var SceneInstrumentation = /** @class */ (function () {
  79576. function SceneInstrumentation(scene) {
  79577. var _this = this;
  79578. this.scene = scene;
  79579. this._captureActiveMeshesEvaluationTime = false;
  79580. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79581. this._captureRenderTargetsRenderTime = false;
  79582. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79583. this._captureFrameTime = false;
  79584. this._frameTime = new BABYLON.PerfCounter();
  79585. this._captureRenderTime = false;
  79586. this._renderTime = new BABYLON.PerfCounter();
  79587. this._captureInterFrameTime = false;
  79588. this._interFrameTime = new BABYLON.PerfCounter();
  79589. this._captureParticlesRenderTime = false;
  79590. this._particlesRenderTime = new BABYLON.PerfCounter();
  79591. this._captureSpritesRenderTime = false;
  79592. this._spritesRenderTime = new BABYLON.PerfCounter();
  79593. this._capturePhysicsTime = false;
  79594. this._physicsTime = new BABYLON.PerfCounter();
  79595. this._captureAnimationsTime = false;
  79596. this._animationsTime = new BABYLON.PerfCounter();
  79597. // Observers
  79598. this._onBeforeActiveMeshesEvaluationObserver = null;
  79599. this._onAfterActiveMeshesEvaluationObserver = null;
  79600. this._onBeforeRenderTargetsRenderObserver = null;
  79601. this._onAfterRenderTargetsRenderObserver = null;
  79602. this._onAfterRenderObserver = null;
  79603. this._onBeforeDrawPhaseObserver = null;
  79604. this._onAfterDrawPhaseObserver = null;
  79605. this._onBeforeAnimationsObserver = null;
  79606. this._onBeforeParticlesRenderingObserver = null;
  79607. this._onAfterParticlesRenderingObserver = null;
  79608. this._onBeforeSpritesRenderingObserver = null;
  79609. this._onAfterSpritesRenderingObserver = null;
  79610. this._onBeforePhysicsObserver = null;
  79611. this._onAfterPhysicsObserver = null;
  79612. this._onAfterAnimationsObserver = null;
  79613. // Before render
  79614. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79615. if (_this._captureActiveMeshesEvaluationTime) {
  79616. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79617. }
  79618. if (_this._captureRenderTargetsRenderTime) {
  79619. _this._renderTargetsRenderTime.fetchNewFrame();
  79620. }
  79621. if (_this._captureFrameTime) {
  79622. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79623. _this._frameTime.beginMonitoring();
  79624. }
  79625. if (_this._captureInterFrameTime) {
  79626. _this._interFrameTime.endMonitoring();
  79627. }
  79628. if (_this._captureParticlesRenderTime) {
  79629. _this._particlesRenderTime.fetchNewFrame();
  79630. }
  79631. if (_this._captureSpritesRenderTime) {
  79632. _this._spritesRenderTime.fetchNewFrame();
  79633. }
  79634. if (_this._captureAnimationsTime) {
  79635. _this._animationsTime.beginMonitoring();
  79636. }
  79637. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79638. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79639. });
  79640. // After render
  79641. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79642. if (_this._captureFrameTime) {
  79643. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79644. _this._frameTime.endMonitoring();
  79645. }
  79646. if (_this._captureRenderTime) {
  79647. _this._renderTime.endMonitoring(false);
  79648. }
  79649. if (_this._captureInterFrameTime) {
  79650. _this._interFrameTime.beginMonitoring();
  79651. }
  79652. });
  79653. }
  79654. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79655. // Properties
  79656. /**
  79657. * Gets the perf counter used for active meshes evaluation time
  79658. */
  79659. get: function () {
  79660. return this._activeMeshesEvaluationTime;
  79661. },
  79662. enumerable: true,
  79663. configurable: true
  79664. });
  79665. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79666. /**
  79667. * Gets the active meshes evaluation time capture status
  79668. */
  79669. get: function () {
  79670. return this._captureActiveMeshesEvaluationTime;
  79671. },
  79672. /**
  79673. * Enable or disable the active meshes evaluation time capture
  79674. */
  79675. set: function (value) {
  79676. var _this = this;
  79677. if (value === this._captureActiveMeshesEvaluationTime) {
  79678. return;
  79679. }
  79680. this._captureActiveMeshesEvaluationTime = value;
  79681. if (value) {
  79682. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79683. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79684. _this._activeMeshesEvaluationTime.beginMonitoring();
  79685. });
  79686. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79687. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79688. _this._activeMeshesEvaluationTime.endMonitoring();
  79689. });
  79690. }
  79691. else {
  79692. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79693. this._onBeforeActiveMeshesEvaluationObserver = null;
  79694. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79695. this._onAfterActiveMeshesEvaluationObserver = null;
  79696. }
  79697. },
  79698. enumerable: true,
  79699. configurable: true
  79700. });
  79701. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79702. /**
  79703. * Gets the perf counter used for render targets render time
  79704. */
  79705. get: function () {
  79706. return this._renderTargetsRenderTime;
  79707. },
  79708. enumerable: true,
  79709. configurable: true
  79710. });
  79711. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79712. /**
  79713. * Gets the render targets render time capture status
  79714. */
  79715. get: function () {
  79716. return this._captureRenderTargetsRenderTime;
  79717. },
  79718. /**
  79719. * Enable or disable the render targets render time capture
  79720. */
  79721. set: function (value) {
  79722. var _this = this;
  79723. if (value === this._captureRenderTargetsRenderTime) {
  79724. return;
  79725. }
  79726. this._captureRenderTargetsRenderTime = value;
  79727. if (value) {
  79728. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79729. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79730. _this._renderTargetsRenderTime.beginMonitoring();
  79731. });
  79732. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79733. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79734. _this._renderTargetsRenderTime.endMonitoring(false);
  79735. });
  79736. }
  79737. else {
  79738. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79739. this._onBeforeRenderTargetsRenderObserver = null;
  79740. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79741. this._onAfterRenderTargetsRenderObserver = null;
  79742. }
  79743. },
  79744. enumerable: true,
  79745. configurable: true
  79746. });
  79747. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79748. /**
  79749. * Gets the perf counter used for particles render time
  79750. */
  79751. get: function () {
  79752. return this._particlesRenderTime;
  79753. },
  79754. enumerable: true,
  79755. configurable: true
  79756. });
  79757. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79758. /**
  79759. * Gets the particles render time capture status
  79760. */
  79761. get: function () {
  79762. return this._captureParticlesRenderTime;
  79763. },
  79764. /**
  79765. * Enable or disable the particles render time capture
  79766. */
  79767. set: function (value) {
  79768. var _this = this;
  79769. if (value === this._captureParticlesRenderTime) {
  79770. return;
  79771. }
  79772. this._captureParticlesRenderTime = value;
  79773. if (value) {
  79774. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79775. BABYLON.Tools.StartPerformanceCounter("Particles");
  79776. _this._particlesRenderTime.beginMonitoring();
  79777. });
  79778. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79779. BABYLON.Tools.EndPerformanceCounter("Particles");
  79780. _this._particlesRenderTime.endMonitoring(false);
  79781. });
  79782. }
  79783. else {
  79784. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79785. this._onBeforeParticlesRenderingObserver = null;
  79786. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79787. this._onAfterParticlesRenderingObserver = null;
  79788. }
  79789. },
  79790. enumerable: true,
  79791. configurable: true
  79792. });
  79793. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79794. /**
  79795. * Gets the perf counter used for sprites render time
  79796. */
  79797. get: function () {
  79798. return this._spritesRenderTime;
  79799. },
  79800. enumerable: true,
  79801. configurable: true
  79802. });
  79803. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79804. /**
  79805. * Gets the sprites render time capture status
  79806. */
  79807. get: function () {
  79808. return this._captureSpritesRenderTime;
  79809. },
  79810. /**
  79811. * Enable or disable the sprites render time capture
  79812. */
  79813. set: function (value) {
  79814. var _this = this;
  79815. if (value === this._captureSpritesRenderTime) {
  79816. return;
  79817. }
  79818. this._captureSpritesRenderTime = value;
  79819. if (value) {
  79820. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79821. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79822. _this._spritesRenderTime.beginMonitoring();
  79823. });
  79824. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79825. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79826. _this._spritesRenderTime.endMonitoring(false);
  79827. });
  79828. }
  79829. else {
  79830. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79831. this._onBeforeSpritesRenderingObserver = null;
  79832. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79833. this._onAfterSpritesRenderingObserver = null;
  79834. }
  79835. },
  79836. enumerable: true,
  79837. configurable: true
  79838. });
  79839. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  79840. /**
  79841. * Gets the perf counter used for physics time
  79842. */
  79843. get: function () {
  79844. return this._physicsTime;
  79845. },
  79846. enumerable: true,
  79847. configurable: true
  79848. });
  79849. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  79850. /**
  79851. * Gets the physics time capture status
  79852. */
  79853. get: function () {
  79854. return this._capturePhysicsTime;
  79855. },
  79856. /**
  79857. * Enable or disable the physics time capture
  79858. */
  79859. set: function (value) {
  79860. var _this = this;
  79861. if (value === this._capturePhysicsTime) {
  79862. return;
  79863. }
  79864. this._capturePhysicsTime = value;
  79865. if (value) {
  79866. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  79867. BABYLON.Tools.StartPerformanceCounter("Physics");
  79868. _this._physicsTime.beginMonitoring();
  79869. });
  79870. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  79871. BABYLON.Tools.EndPerformanceCounter("Physics");
  79872. _this._physicsTime.endMonitoring();
  79873. });
  79874. }
  79875. else {
  79876. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79877. this._onBeforePhysicsObserver = null;
  79878. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79879. this._onAfterPhysicsObserver = null;
  79880. }
  79881. },
  79882. enumerable: true,
  79883. configurable: true
  79884. });
  79885. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  79886. /**
  79887. * Gets the perf counter used for animations time
  79888. */
  79889. get: function () {
  79890. return this._animationsTime;
  79891. },
  79892. enumerable: true,
  79893. configurable: true
  79894. });
  79895. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  79896. /**
  79897. * Gets the animations time capture status
  79898. */
  79899. get: function () {
  79900. return this._captureAnimationsTime;
  79901. },
  79902. /**
  79903. * Enable or disable the animations time capture
  79904. */
  79905. set: function (value) {
  79906. var _this = this;
  79907. if (value === this._captureAnimationsTime) {
  79908. return;
  79909. }
  79910. this._captureAnimationsTime = value;
  79911. if (value) {
  79912. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  79913. _this._animationsTime.endMonitoring();
  79914. });
  79915. }
  79916. else {
  79917. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79918. this._onAfterAnimationsObserver = null;
  79919. }
  79920. },
  79921. enumerable: true,
  79922. configurable: true
  79923. });
  79924. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  79925. /**
  79926. * Gets the perf counter used for frame time capture
  79927. */
  79928. get: function () {
  79929. return this._frameTime;
  79930. },
  79931. enumerable: true,
  79932. configurable: true
  79933. });
  79934. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  79935. /**
  79936. * Gets the frame time capture status
  79937. */
  79938. get: function () {
  79939. return this._captureFrameTime;
  79940. },
  79941. /**
  79942. * Enable or disable the frame time capture
  79943. */
  79944. set: function (value) {
  79945. this._captureFrameTime = value;
  79946. },
  79947. enumerable: true,
  79948. configurable: true
  79949. });
  79950. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  79951. /**
  79952. * Gets the perf counter used for inter-frames time capture
  79953. */
  79954. get: function () {
  79955. return this._interFrameTime;
  79956. },
  79957. enumerable: true,
  79958. configurable: true
  79959. });
  79960. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  79961. /**
  79962. * Gets the inter-frames time capture status
  79963. */
  79964. get: function () {
  79965. return this._captureInterFrameTime;
  79966. },
  79967. /**
  79968. * Enable or disable the inter-frames time capture
  79969. */
  79970. set: function (value) {
  79971. this._captureInterFrameTime = value;
  79972. },
  79973. enumerable: true,
  79974. configurable: true
  79975. });
  79976. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  79977. /**
  79978. * Gets the perf counter used for render time capture
  79979. */
  79980. get: function () {
  79981. return this._renderTime;
  79982. },
  79983. enumerable: true,
  79984. configurable: true
  79985. });
  79986. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  79987. /**
  79988. * Gets the render time capture status
  79989. */
  79990. get: function () {
  79991. return this._captureRenderTime;
  79992. },
  79993. /**
  79994. * Enable or disable the render time capture
  79995. */
  79996. set: function (value) {
  79997. var _this = this;
  79998. if (value === this._captureRenderTime) {
  79999. return;
  80000. }
  80001. this._captureRenderTime = value;
  80002. if (value) {
  80003. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  80004. _this._renderTime.beginMonitoring();
  80005. BABYLON.Tools.StartPerformanceCounter("Main render");
  80006. });
  80007. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  80008. _this._renderTime.endMonitoring(false);
  80009. BABYLON.Tools.EndPerformanceCounter("Main render");
  80010. });
  80011. }
  80012. else {
  80013. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80014. this._onBeforeDrawPhaseObserver = null;
  80015. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80016. this._onAfterDrawPhaseObserver = null;
  80017. }
  80018. },
  80019. enumerable: true,
  80020. configurable: true
  80021. });
  80022. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  80023. /**
  80024. * Gets the perf counter used for draw calls
  80025. */
  80026. get: function () {
  80027. return this.scene.getEngine()._drawCalls;
  80028. },
  80029. enumerable: true,
  80030. configurable: true
  80031. });
  80032. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80033. /**
  80034. * Gets the perf counter used for texture collisions
  80035. */
  80036. get: function () {
  80037. return this.scene.getEngine()._textureCollisions;
  80038. },
  80039. enumerable: true,
  80040. configurable: true
  80041. });
  80042. SceneInstrumentation.prototype.dispose = function () {
  80043. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80044. this._onAfterRenderObserver = null;
  80045. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80046. this._onBeforeActiveMeshesEvaluationObserver = null;
  80047. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80048. this._onAfterActiveMeshesEvaluationObserver = null;
  80049. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80050. this._onBeforeRenderTargetsRenderObserver = null;
  80051. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80052. this._onAfterRenderTargetsRenderObserver = null;
  80053. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80054. this._onBeforeAnimationsObserver = null;
  80055. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80056. this._onBeforeParticlesRenderingObserver = null;
  80057. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80058. this._onAfterParticlesRenderingObserver = null;
  80059. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80060. this._onBeforeSpritesRenderingObserver = null;
  80061. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80062. this._onAfterSpritesRenderingObserver = null;
  80063. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80064. this._onBeforeDrawPhaseObserver = null;
  80065. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80066. this._onAfterDrawPhaseObserver = null;
  80067. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80068. this._onBeforePhysicsObserver = null;
  80069. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80070. this._onAfterPhysicsObserver = null;
  80071. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80072. this._onAfterAnimationsObserver = null;
  80073. this.scene = null;
  80074. };
  80075. return SceneInstrumentation;
  80076. }());
  80077. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80078. })(BABYLON || (BABYLON = {}));
  80079. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80080. var BABYLON;
  80081. (function (BABYLON) {
  80082. var _TimeToken = /** @class */ (function () {
  80083. function _TimeToken() {
  80084. this._timeElapsedQueryEnded = false;
  80085. }
  80086. return _TimeToken;
  80087. }());
  80088. BABYLON._TimeToken = _TimeToken;
  80089. })(BABYLON || (BABYLON = {}));
  80090. //# sourceMappingURL=babylon.timeToken.js.map
  80091. var BABYLON;
  80092. (function (BABYLON) {
  80093. /**
  80094. * Background material defines definition.
  80095. */
  80096. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80097. __extends(BackgroundMaterialDefines, _super);
  80098. /**
  80099. * Constructor of the defines.
  80100. */
  80101. function BackgroundMaterialDefines() {
  80102. var _this = _super.call(this) || this;
  80103. /**
  80104. * True if the diffuse texture is in use.
  80105. */
  80106. _this.DIFFUSE = false;
  80107. /**
  80108. * The direct UV channel to use.
  80109. */
  80110. _this.DIFFUSEDIRECTUV = 0;
  80111. /**
  80112. * True if the diffuse texture is in gamma space.
  80113. */
  80114. _this.GAMMADIFFUSE = false;
  80115. /**
  80116. * True if the diffuse texture has opacity in the alpha channel.
  80117. */
  80118. _this.DIFFUSEHASALPHA = false;
  80119. /**
  80120. * True if you want the material to fade to transparent at grazing angle.
  80121. */
  80122. _this.OPACITYFRESNEL = false;
  80123. /**
  80124. * True if an extra blur needs to be added in the reflection.
  80125. */
  80126. _this.REFLECTIONBLUR = false;
  80127. /**
  80128. * True if you want the material to fade to reflection at grazing angle.
  80129. */
  80130. _this.REFLECTIONFRESNEL = false;
  80131. /**
  80132. * True if you want the material to falloff as far as you move away from the scene center.
  80133. */
  80134. _this.REFLECTIONFALLOFF = false;
  80135. /**
  80136. * False if the current Webgl implementation does not support the texture lod extension.
  80137. */
  80138. _this.TEXTURELODSUPPORT = false;
  80139. /**
  80140. * True to ensure the data are premultiplied.
  80141. */
  80142. _this.PREMULTIPLYALPHA = false;
  80143. /**
  80144. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80145. */
  80146. _this.USERGBCOLOR = false;
  80147. /**
  80148. * True to add noise in order to reduce the banding effect.
  80149. */
  80150. _this.NOISE = false;
  80151. // Image Processing Configuration.
  80152. _this.IMAGEPROCESSING = false;
  80153. _this.VIGNETTE = false;
  80154. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80155. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80156. _this.TONEMAPPING = false;
  80157. _this.CONTRAST = false;
  80158. _this.COLORCURVES = false;
  80159. _this.COLORGRADING = false;
  80160. _this.COLORGRADING3D = false;
  80161. _this.SAMPLER3DGREENDEPTH = false;
  80162. _this.SAMPLER3DBGRMAP = false;
  80163. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80164. _this.EXPOSURE = false;
  80165. // Reflection.
  80166. _this.REFLECTION = false;
  80167. _this.REFLECTIONMAP_3D = false;
  80168. _this.REFLECTIONMAP_SPHERICAL = false;
  80169. _this.REFLECTIONMAP_PLANAR = false;
  80170. _this.REFLECTIONMAP_CUBIC = false;
  80171. _this.REFLECTIONMAP_PROJECTION = false;
  80172. _this.REFLECTIONMAP_SKYBOX = false;
  80173. _this.REFLECTIONMAP_EXPLICIT = false;
  80174. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80175. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80176. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80177. _this.INVERTCUBICMAP = false;
  80178. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80179. _this.LODINREFLECTIONALPHA = false;
  80180. _this.GAMMAREFLECTION = false;
  80181. // Default BJS.
  80182. _this.MAINUV1 = false;
  80183. _this.MAINUV2 = false;
  80184. _this.UV1 = false;
  80185. _this.UV2 = false;
  80186. _this.CLIPPLANE = false;
  80187. _this.POINTSIZE = false;
  80188. _this.FOG = false;
  80189. _this.NORMAL = false;
  80190. _this.NUM_BONE_INFLUENCERS = 0;
  80191. _this.BonesPerMesh = 0;
  80192. _this.INSTANCES = false;
  80193. _this.SHADOWFLOAT = false;
  80194. _this.rebuild();
  80195. return _this;
  80196. }
  80197. return BackgroundMaterialDefines;
  80198. }(BABYLON.MaterialDefines));
  80199. /**
  80200. * Background material used to create an efficient environement around your scene.
  80201. */
  80202. var BackgroundMaterial = /** @class */ (function (_super) {
  80203. __extends(BackgroundMaterial, _super);
  80204. /**
  80205. * constructor
  80206. * @param name The name of the material
  80207. * @param scene The scene to add the material to
  80208. */
  80209. function BackgroundMaterial(name, scene) {
  80210. var _this = _super.call(this, name, scene) || this;
  80211. _this.primaryColor = BABYLON.Color3.White();
  80212. _this.primaryLevel = 1;
  80213. _this.secondaryColor = BABYLON.Color3.Gray();
  80214. _this.secondaryLevel = 1;
  80215. _this.tertiaryColor = BABYLON.Color3.Black();
  80216. _this.tertiaryLevel = 1;
  80217. _this.reflectionTexture = null;
  80218. _this.reflectionBlur = 0;
  80219. _this.diffuseTexture = null;
  80220. /**
  80221. * Specify the list of lights casting shadow on the material.
  80222. * All scene shadow lights will be included if null.
  80223. */
  80224. _this._shadowLights = null;
  80225. _this.shadowLights = null;
  80226. _this.shadowBlurScale = 1;
  80227. _this.shadowLevel = 0;
  80228. _this.sceneCenter = BABYLON.Vector3.Zero();
  80229. _this.opacityFresnel = true;
  80230. _this.reflectionFresnel = false;
  80231. _this.reflectionFalloffDistance = 0.0;
  80232. _this.reflectionAmount = 1.0;
  80233. _this.reflectionReflectance0 = 0.05;
  80234. _this.reflectionReflectance90 = 0.5;
  80235. _this.useRGBColor = true;
  80236. _this.enableNoise = false;
  80237. /**
  80238. * Number of Simultaneous lights allowed on the material.
  80239. */
  80240. _this._maxSimultaneousLights = 4;
  80241. _this.maxSimultaneousLights = 4;
  80242. /**
  80243. * Keep track of the image processing observer to allow dispose and replace.
  80244. */
  80245. _this._imageProcessingObserver = null;
  80246. // Temp values kept as cache in the material.
  80247. _this._renderTargets = new BABYLON.SmartArray(16);
  80248. _this._reflectionControls = BABYLON.Vector4.Zero();
  80249. // Setup the default processing configuration to the scene.
  80250. _this._attachImageProcessingConfiguration(null);
  80251. _this.getRenderTargetTextures = function () {
  80252. _this._renderTargets.reset();
  80253. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80254. _this._renderTargets.push(_this._diffuseTexture);
  80255. }
  80256. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80257. _this._renderTargets.push(_this._reflectionTexture);
  80258. }
  80259. return _this._renderTargets;
  80260. };
  80261. return _this;
  80262. }
  80263. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80264. /**
  80265. * Sets the reflection reflectance fresnel values according to the default standard
  80266. * empirically know to work well :-)
  80267. */
  80268. set: function (value) {
  80269. var reflectionWeight = value;
  80270. if (reflectionWeight < 0.5) {
  80271. reflectionWeight = reflectionWeight * 2.0;
  80272. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80273. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80274. }
  80275. else {
  80276. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80277. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80278. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80279. }
  80280. },
  80281. enumerable: true,
  80282. configurable: true
  80283. });
  80284. /**
  80285. * Attaches a new image processing configuration to the PBR Material.
  80286. * @param configuration (if null the scene configuration will be use)
  80287. */
  80288. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80289. var _this = this;
  80290. if (configuration === this._imageProcessingConfiguration) {
  80291. return;
  80292. }
  80293. // Detaches observer.
  80294. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80295. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80296. }
  80297. // Pick the scene configuration if needed.
  80298. if (!configuration) {
  80299. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80300. }
  80301. else {
  80302. this._imageProcessingConfiguration = configuration;
  80303. }
  80304. // Attaches observer.
  80305. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80306. _this._markAllSubMeshesAsImageProcessingDirty();
  80307. });
  80308. };
  80309. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80310. /**
  80311. * Gets the image processing configuration used either in this material.
  80312. */
  80313. get: function () {
  80314. return this._imageProcessingConfiguration;
  80315. },
  80316. /**
  80317. * Sets the Default image processing configuration used either in the this material.
  80318. *
  80319. * If sets to null, the scene one is in use.
  80320. */
  80321. set: function (value) {
  80322. this._attachImageProcessingConfiguration(value);
  80323. // Ensure the effect will be rebuilt.
  80324. this._markAllSubMeshesAsTexturesDirty();
  80325. },
  80326. enumerable: true,
  80327. configurable: true
  80328. });
  80329. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80330. /**
  80331. * Gets wether the color curves effect is enabled.
  80332. */
  80333. get: function () {
  80334. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80335. },
  80336. /**
  80337. * Sets wether the color curves effect is enabled.
  80338. */
  80339. set: function (value) {
  80340. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80341. },
  80342. enumerable: true,
  80343. configurable: true
  80344. });
  80345. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80346. /**
  80347. * Gets wether the color grading effect is enabled.
  80348. */
  80349. get: function () {
  80350. return this.imageProcessingConfiguration.colorGradingEnabled;
  80351. },
  80352. /**
  80353. * Gets wether the color grading effect is enabled.
  80354. */
  80355. set: function (value) {
  80356. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80357. },
  80358. enumerable: true,
  80359. configurable: true
  80360. });
  80361. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80362. /**
  80363. * Gets wether tonemapping is enabled or not.
  80364. */
  80365. get: function () {
  80366. return this._imageProcessingConfiguration.toneMappingEnabled;
  80367. },
  80368. /**
  80369. * Sets wether tonemapping is enabled or not
  80370. */
  80371. set: function (value) {
  80372. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80373. },
  80374. enumerable: true,
  80375. configurable: true
  80376. });
  80377. ;
  80378. ;
  80379. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80380. /**
  80381. * The camera exposure used on this material.
  80382. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80383. * This corresponds to a photographic exposure.
  80384. */
  80385. get: function () {
  80386. return this._imageProcessingConfiguration.exposure;
  80387. },
  80388. /**
  80389. * The camera exposure used on this material.
  80390. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80391. * This corresponds to a photographic exposure.
  80392. */
  80393. set: function (value) {
  80394. this._imageProcessingConfiguration.exposure = value;
  80395. },
  80396. enumerable: true,
  80397. configurable: true
  80398. });
  80399. ;
  80400. ;
  80401. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80402. /**
  80403. * Gets The camera contrast used on this material.
  80404. */
  80405. get: function () {
  80406. return this._imageProcessingConfiguration.contrast;
  80407. },
  80408. /**
  80409. * Sets The camera contrast used on this material.
  80410. */
  80411. set: function (value) {
  80412. this._imageProcessingConfiguration.contrast = value;
  80413. },
  80414. enumerable: true,
  80415. configurable: true
  80416. });
  80417. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80418. /**
  80419. * Gets the Color Grading 2D Lookup Texture.
  80420. */
  80421. get: function () {
  80422. return this._imageProcessingConfiguration.colorGradingTexture;
  80423. },
  80424. /**
  80425. * Sets the Color Grading 2D Lookup Texture.
  80426. */
  80427. set: function (value) {
  80428. this.imageProcessingConfiguration.colorGradingTexture = value;
  80429. },
  80430. enumerable: true,
  80431. configurable: true
  80432. });
  80433. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80434. /**
  80435. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80436. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80437. * 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;
  80438. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80439. */
  80440. get: function () {
  80441. return this.imageProcessingConfiguration.colorCurves;
  80442. },
  80443. /**
  80444. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80445. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80446. * 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;
  80447. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80448. */
  80449. set: function (value) {
  80450. this.imageProcessingConfiguration.colorCurves = value;
  80451. },
  80452. enumerable: true,
  80453. configurable: true
  80454. });
  80455. /**
  80456. * The entire material has been created in order to prevent overdraw.
  80457. * @returns false
  80458. */
  80459. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80460. return true;
  80461. };
  80462. /**
  80463. * The entire material has been created in order to prevent overdraw.
  80464. * @returns true if blending is enable
  80465. */
  80466. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80467. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80468. };
  80469. /**
  80470. * Checks wether the material is ready to be rendered for a given mesh.
  80471. * @param mesh The mesh to render
  80472. * @param subMesh The submesh to check against
  80473. * @param useInstances Specify wether or not the material is used with instances
  80474. */
  80475. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80476. var _this = this;
  80477. if (useInstances === void 0) { useInstances = false; }
  80478. if (subMesh.effect && this.isFrozen) {
  80479. if (this._wasPreviouslyReady) {
  80480. return true;
  80481. }
  80482. }
  80483. if (!subMesh._materialDefines) {
  80484. subMesh._materialDefines = new BackgroundMaterialDefines();
  80485. }
  80486. var scene = this.getScene();
  80487. var defines = subMesh._materialDefines;
  80488. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80489. if (defines._renderId === scene.getRenderId()) {
  80490. return true;
  80491. }
  80492. }
  80493. var engine = scene.getEngine();
  80494. // Lights
  80495. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80496. defines._needNormals = true;
  80497. // Textures
  80498. if (defines._areTexturesDirty) {
  80499. defines._needUVs = false;
  80500. if (scene.texturesEnabled) {
  80501. if (scene.getEngine().getCaps().textureLOD) {
  80502. defines.TEXTURELODSUPPORT = true;
  80503. }
  80504. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80505. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80506. return false;
  80507. }
  80508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80509. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80510. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80511. defines.OPACITYFRESNEL = this._opacityFresnel;
  80512. }
  80513. else {
  80514. defines.DIFFUSE = false;
  80515. defines.DIFFUSEHASALPHA = false;
  80516. defines.GAMMADIFFUSE = false;
  80517. defines.OPACITYFRESNEL = false;
  80518. }
  80519. var reflectionTexture = this._reflectionTexture;
  80520. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80521. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80522. return false;
  80523. }
  80524. defines.REFLECTION = true;
  80525. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80526. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80527. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80528. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80529. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80530. defines.INVERTCUBICMAP = true;
  80531. }
  80532. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80533. switch (reflectionTexture.coordinatesMode) {
  80534. case BABYLON.Texture.CUBIC_MODE:
  80535. case BABYLON.Texture.INVCUBIC_MODE:
  80536. defines.REFLECTIONMAP_CUBIC = true;
  80537. break;
  80538. case BABYLON.Texture.EXPLICIT_MODE:
  80539. defines.REFLECTIONMAP_EXPLICIT = true;
  80540. break;
  80541. case BABYLON.Texture.PLANAR_MODE:
  80542. defines.REFLECTIONMAP_PLANAR = true;
  80543. break;
  80544. case BABYLON.Texture.PROJECTION_MODE:
  80545. defines.REFLECTIONMAP_PROJECTION = true;
  80546. break;
  80547. case BABYLON.Texture.SKYBOX_MODE:
  80548. defines.REFLECTIONMAP_SKYBOX = true;
  80549. break;
  80550. case BABYLON.Texture.SPHERICAL_MODE:
  80551. defines.REFLECTIONMAP_SPHERICAL = true;
  80552. break;
  80553. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80554. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80555. break;
  80556. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80557. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80558. break;
  80559. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80560. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80561. break;
  80562. }
  80563. if (this.reflectionFresnel) {
  80564. defines.REFLECTIONFRESNEL = true;
  80565. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80566. this._reflectionControls.x = this.reflectionAmount;
  80567. this._reflectionControls.y = this.reflectionReflectance0;
  80568. this._reflectionControls.z = this.reflectionReflectance90;
  80569. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80570. }
  80571. else {
  80572. defines.REFLECTIONFRESNEL = false;
  80573. defines.REFLECTIONFALLOFF = false;
  80574. }
  80575. }
  80576. else {
  80577. defines.REFLECTION = false;
  80578. defines.REFLECTIONFALLOFF = false;
  80579. defines.REFLECTIONBLUR = false;
  80580. defines.REFLECTIONMAP_3D = false;
  80581. defines.REFLECTIONMAP_SPHERICAL = false;
  80582. defines.REFLECTIONMAP_PLANAR = false;
  80583. defines.REFLECTIONMAP_CUBIC = false;
  80584. defines.REFLECTIONMAP_PROJECTION = false;
  80585. defines.REFLECTIONMAP_SKYBOX = false;
  80586. defines.REFLECTIONMAP_EXPLICIT = false;
  80587. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80588. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80589. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80590. defines.INVERTCUBICMAP = false;
  80591. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80592. defines.LODINREFLECTIONALPHA = false;
  80593. defines.GAMMAREFLECTION = false;
  80594. }
  80595. }
  80596. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80597. defines.USERGBCOLOR = this._useRGBColor;
  80598. defines.NOISE = this._enableNoise;
  80599. }
  80600. if (defines._areImageProcessingDirty) {
  80601. if (!this._imageProcessingConfiguration.isReady()) {
  80602. return false;
  80603. }
  80604. this._imageProcessingConfiguration.prepareDefines(defines);
  80605. }
  80606. // Misc.
  80607. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80608. // Values that need to be evaluated on every frame
  80609. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  80610. // Attribs
  80611. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80612. if (mesh) {
  80613. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80614. mesh.createNormals(true);
  80615. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80616. }
  80617. }
  80618. }
  80619. // Get correct effect
  80620. if (defines.isDirty) {
  80621. defines.markAsProcessed();
  80622. scene.resetCachedMaterial();
  80623. // Fallbacks
  80624. var fallbacks = new BABYLON.EffectFallbacks();
  80625. if (defines.FOG) {
  80626. fallbacks.addFallback(0, "FOG");
  80627. }
  80628. if (defines.POINTSIZE) {
  80629. fallbacks.addFallback(1, "POINTSIZE");
  80630. }
  80631. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80632. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80633. fallbacks.addCPUSkinningFallback(0, mesh);
  80634. }
  80635. //Attributes
  80636. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80637. if (defines.NORMAL) {
  80638. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80639. }
  80640. if (defines.UV1) {
  80641. attribs.push(BABYLON.VertexBuffer.UVKind);
  80642. }
  80643. if (defines.UV2) {
  80644. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80645. }
  80646. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80647. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80648. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80649. "vFogInfos", "vFogColor", "pointSize",
  80650. "vClipPlane", "mBones",
  80651. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80652. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80653. "shadowLevel", "alpha",
  80654. "vBackgroundCenter", "vReflectionControl",
  80655. "vDiffuseInfos", "diffuseMatrix",
  80656. ];
  80657. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80658. var uniformBuffers = ["Material", "Scene"];
  80659. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80660. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80661. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80662. uniformsNames: uniforms,
  80663. uniformBuffersNames: uniformBuffers,
  80664. samplers: samplers,
  80665. defines: defines,
  80666. maxSimultaneousLights: this._maxSimultaneousLights
  80667. });
  80668. var onCompiled = function (effect) {
  80669. if (_this.onCompiled) {
  80670. _this.onCompiled(effect);
  80671. }
  80672. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80673. };
  80674. var join = defines.toString();
  80675. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80676. attributes: attribs,
  80677. uniformsNames: uniforms,
  80678. uniformBuffersNames: uniformBuffers,
  80679. samplers: samplers,
  80680. defines: join,
  80681. fallbacks: fallbacks,
  80682. onCompiled: onCompiled,
  80683. onError: this.onError,
  80684. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80685. }, engine), defines);
  80686. this.buildUniformLayout();
  80687. }
  80688. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80689. return false;
  80690. }
  80691. defines._renderId = scene.getRenderId();
  80692. this._wasPreviouslyReady = true;
  80693. return true;
  80694. };
  80695. /**
  80696. * Build the uniform buffer used in the material.
  80697. */
  80698. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80699. // Order is important !
  80700. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80701. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80702. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80703. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80704. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80705. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80706. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80707. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80708. this._uniformBuffer.addUniform("pointSize", 1);
  80709. this._uniformBuffer.addUniform("shadowLevel", 1);
  80710. this._uniformBuffer.addUniform("alpha", 1);
  80711. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80712. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80713. this._uniformBuffer.create();
  80714. };
  80715. /**
  80716. * Unbind the material.
  80717. */
  80718. BackgroundMaterial.prototype.unbind = function () {
  80719. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80720. this._uniformBuffer.setTexture("diffuseSampler", null);
  80721. }
  80722. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80723. this._uniformBuffer.setTexture("reflectionSampler", null);
  80724. }
  80725. _super.prototype.unbind.call(this);
  80726. };
  80727. /**
  80728. * Bind only the world matrix to the material.
  80729. * @param world The world matrix to bind.
  80730. */
  80731. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80732. this._activeEffect.setMatrix("world", world);
  80733. };
  80734. /**
  80735. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80736. * @param world The world matrix to bind.
  80737. * @param subMesh The submesh to bind for.
  80738. */
  80739. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80740. var scene = this.getScene();
  80741. var defines = subMesh._materialDefines;
  80742. if (!defines) {
  80743. return;
  80744. }
  80745. var effect = subMesh.effect;
  80746. if (!effect) {
  80747. return;
  80748. }
  80749. this._activeEffect = effect;
  80750. // Matrices
  80751. this.bindOnlyWorldMatrix(world);
  80752. // Bones
  80753. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80754. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80755. if (mustRebind) {
  80756. this._uniformBuffer.bindToEffect(effect, "Material");
  80757. this.bindViewProjection(effect);
  80758. var reflectionTexture = this._reflectionTexture;
  80759. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80760. // Texture uniforms
  80761. if (scene.texturesEnabled) {
  80762. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80763. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80764. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80765. }
  80766. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80767. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80768. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80769. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80770. }
  80771. }
  80772. if (this.shadowLevel > 0) {
  80773. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80774. }
  80775. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80776. // Point size
  80777. if (this.pointsCloud) {
  80778. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80779. }
  80780. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80781. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80782. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80783. }
  80784. // Textures
  80785. if (scene.texturesEnabled) {
  80786. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80787. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80788. }
  80789. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80790. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80791. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80792. }
  80793. else if (!defines.REFLECTIONBLUR) {
  80794. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80795. }
  80796. else {
  80797. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80798. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80799. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80800. }
  80801. if (defines.REFLECTIONFRESNEL) {
  80802. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80803. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80804. }
  80805. }
  80806. }
  80807. // Clip plane
  80808. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80809. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80810. }
  80811. if (mustRebind || !this.isFrozen) {
  80812. if (scene.lightsEnabled) {
  80813. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80814. }
  80815. // View
  80816. this.bindView(effect);
  80817. // Fog
  80818. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80819. // image processing
  80820. this._imageProcessingConfiguration.bind(this._activeEffect);
  80821. }
  80822. this._uniformBuffer.update();
  80823. this._afterBind(mesh);
  80824. };
  80825. /**
  80826. * Dispose the material.
  80827. * @forceDisposeEffect Force disposal of the associated effect.
  80828. * @forceDisposeTextures Force disposal of the associated textures.
  80829. */
  80830. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80831. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80832. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80833. if (forceDisposeTextures) {
  80834. if (this.diffuseTexture) {
  80835. this.diffuseTexture.dispose();
  80836. }
  80837. if (this.reflectionTexture) {
  80838. this.reflectionTexture.dispose();
  80839. }
  80840. }
  80841. this._renderTargets.dispose();
  80842. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80843. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80844. }
  80845. _super.prototype.dispose.call(this, forceDisposeEffect);
  80846. };
  80847. /**
  80848. * Clones the material.
  80849. * @name The cloned name.
  80850. * @returns The cloned material.
  80851. */
  80852. BackgroundMaterial.prototype.clone = function (name) {
  80853. var _this = this;
  80854. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  80855. };
  80856. /**
  80857. * Serializes the current material to its JSON representation.
  80858. * @returns The JSON representation.
  80859. */
  80860. BackgroundMaterial.prototype.serialize = function () {
  80861. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80862. serializationObject.customType = "BABYLON.BackgroundMaterial";
  80863. return serializationObject;
  80864. };
  80865. /**
  80866. * Gets the class name of the material
  80867. * @returns "BackgroundMaterial"
  80868. */
  80869. BackgroundMaterial.prototype.getClassName = function () {
  80870. return "BackgroundMaterial";
  80871. };
  80872. /**
  80873. * Parse a JSON input to create back a background material.
  80874. * @param source
  80875. * @param scene
  80876. * @param rootUrl
  80877. * @returns the instantiated BackgroundMaterial.
  80878. */
  80879. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  80880. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  80881. };
  80882. /**
  80883. * Standard reflectance value at parallel view angle.
  80884. */
  80885. BackgroundMaterial.standardReflectance0 = 0.05;
  80886. /**
  80887. * Standard reflectance value at grazing angle.
  80888. */
  80889. BackgroundMaterial.standardReflectance90 = 0.5;
  80890. __decorate([
  80891. BABYLON.serializeAsColor3()
  80892. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  80893. __decorate([
  80894. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80895. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  80896. __decorate([
  80897. BABYLON.serialize()
  80898. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  80899. __decorate([
  80900. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80901. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  80902. __decorate([
  80903. BABYLON.serializeAsColor3()
  80904. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  80905. __decorate([
  80906. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80907. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  80908. __decorate([
  80909. BABYLON.serialize()
  80910. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  80911. __decorate([
  80912. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80913. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  80914. __decorate([
  80915. BABYLON.serializeAsColor3()
  80916. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  80917. __decorate([
  80918. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80919. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  80920. __decorate([
  80921. BABYLON.serialize()
  80922. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  80923. __decorate([
  80924. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80925. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  80926. __decorate([
  80927. BABYLON.serializeAsTexture()
  80928. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  80929. __decorate([
  80930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80931. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  80932. __decorate([
  80933. BABYLON.serialize()
  80934. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  80935. __decorate([
  80936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80937. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  80938. __decorate([
  80939. BABYLON.serializeAsTexture()
  80940. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  80941. __decorate([
  80942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80943. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  80944. __decorate([
  80945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80946. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  80947. __decorate([
  80948. BABYLON.serialize()
  80949. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  80950. __decorate([
  80951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80952. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  80953. __decorate([
  80954. BABYLON.serialize()
  80955. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  80956. __decorate([
  80957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80958. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  80959. __decorate([
  80960. BABYLON.serializeAsVector3()
  80961. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  80962. __decorate([
  80963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80964. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  80965. __decorate([
  80966. BABYLON.serialize()
  80967. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  80968. __decorate([
  80969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80970. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  80971. __decorate([
  80972. BABYLON.serialize()
  80973. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  80974. __decorate([
  80975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80976. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  80977. __decorate([
  80978. BABYLON.serialize()
  80979. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  80980. __decorate([
  80981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80982. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  80983. __decorate([
  80984. BABYLON.serialize()
  80985. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  80986. __decorate([
  80987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80988. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  80989. __decorate([
  80990. BABYLON.serialize()
  80991. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  80992. __decorate([
  80993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80994. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  80995. __decorate([
  80996. BABYLON.serialize()
  80997. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  80998. __decorate([
  80999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81000. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  81001. __decorate([
  81002. BABYLON.serialize()
  81003. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  81004. __decorate([
  81005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81006. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  81007. __decorate([
  81008. BABYLON.serialize()
  81009. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  81010. __decorate([
  81011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81012. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  81013. __decorate([
  81014. BABYLON.serialize()
  81015. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  81016. __decorate([
  81017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81018. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  81019. __decorate([
  81020. BABYLON.serializeAsImageProcessingConfiguration()
  81021. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  81022. return BackgroundMaterial;
  81023. }(BABYLON.PushMaterial));
  81024. BABYLON.BackgroundMaterial = BackgroundMaterial;
  81025. })(BABYLON || (BABYLON = {}));
  81026. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  81027. var __assign = (this && this.__assign) || Object.assign || function(t) {
  81028. for (var s, i = 1, n = arguments.length; i < n; i++) {
  81029. s = arguments[i];
  81030. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81031. t[p] = s[p];
  81032. }
  81033. return t;
  81034. };
  81035. var BABYLON;
  81036. (function (BABYLON) {
  81037. /**
  81038. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81039. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81040. * It also helps with the default setup of your imageProcessing configuration.
  81041. */
  81042. var EnvironmentHelper = /** @class */ (function () {
  81043. /**
  81044. * constructor
  81045. * @param options
  81046. * @param scene The scene to add the material to
  81047. */
  81048. function EnvironmentHelper(options, scene) {
  81049. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81050. this._scene = scene;
  81051. this._setupBackground();
  81052. this._setupImageProcessing();
  81053. }
  81054. /**
  81055. * Creates the default options for the helper.
  81056. */
  81057. EnvironmentHelper._getDefaultOptions = function () {
  81058. return {
  81059. createGround: true,
  81060. groundSize: 15,
  81061. groundTexture: this._groundTextureCDNUrl,
  81062. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81063. groundOpacity: 0.9,
  81064. enableGroundShadow: true,
  81065. groundShadowLevel: 0.5,
  81066. enableGroundMirror: false,
  81067. groundMirrorSizeRatio: 0.3,
  81068. groundMirrorBlurKernel: 64,
  81069. groundMirrorAmount: 1,
  81070. groundMirrorFresnelWeight: 1,
  81071. groundMirrorFallOffDistance: 0,
  81072. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81073. groundYBias: 0.00001,
  81074. createSkybox: true,
  81075. skyboxSize: 20,
  81076. skyboxTexture: this._skyboxTextureCDNUrl,
  81077. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81078. backgroundYRotation: 0,
  81079. sizeAuto: true,
  81080. rootPosition: BABYLON.Vector3.Zero(),
  81081. setupImageProcessing: true,
  81082. environmentTexture: this._environmentTextureCDNUrl,
  81083. cameraExposure: 0.8,
  81084. cameraContrast: 1.2,
  81085. toneMappingEnabled: true,
  81086. };
  81087. };
  81088. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81089. /**
  81090. * Gets the root mesh created by the helper.
  81091. */
  81092. get: function () {
  81093. return this._rootMesh;
  81094. },
  81095. enumerable: true,
  81096. configurable: true
  81097. });
  81098. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81099. /**
  81100. * Gets the skybox created by the helper.
  81101. */
  81102. get: function () {
  81103. return this._skybox;
  81104. },
  81105. enumerable: true,
  81106. configurable: true
  81107. });
  81108. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81109. /**
  81110. * Gets the skybox texture created by the helper.
  81111. */
  81112. get: function () {
  81113. return this._skyboxTexture;
  81114. },
  81115. enumerable: true,
  81116. configurable: true
  81117. });
  81118. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81119. /**
  81120. * Gets the skybox material created by the helper.
  81121. */
  81122. get: function () {
  81123. return this._skyboxMaterial;
  81124. },
  81125. enumerable: true,
  81126. configurable: true
  81127. });
  81128. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81129. /**
  81130. * Gets the ground mesh created by the helper.
  81131. */
  81132. get: function () {
  81133. return this._ground;
  81134. },
  81135. enumerable: true,
  81136. configurable: true
  81137. });
  81138. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81139. /**
  81140. * Gets the ground texture created by the helper.
  81141. */
  81142. get: function () {
  81143. return this._groundTexture;
  81144. },
  81145. enumerable: true,
  81146. configurable: true
  81147. });
  81148. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81149. /**
  81150. * Gets the ground mirror created by the helper.
  81151. */
  81152. get: function () {
  81153. return this._groundMirror;
  81154. },
  81155. enumerable: true,
  81156. configurable: true
  81157. });
  81158. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81159. /**
  81160. * Gets the ground mirror render list to helps pushing the meshes
  81161. * you wish in the ground reflection.
  81162. */
  81163. get: function () {
  81164. if (this._groundMirror) {
  81165. return this._groundMirror.renderList;
  81166. }
  81167. return null;
  81168. },
  81169. enumerable: true,
  81170. configurable: true
  81171. });
  81172. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81173. /**
  81174. * Gets the ground material created by the helper.
  81175. */
  81176. get: function () {
  81177. return this._groundMaterial;
  81178. },
  81179. enumerable: true,
  81180. configurable: true
  81181. });
  81182. /**
  81183. * Updates the background according to the new options
  81184. * @param options
  81185. */
  81186. EnvironmentHelper.prototype.updateOptions = function (options) {
  81187. var newOptions = __assign({}, this._options, options);
  81188. if (this._ground && !newOptions.createGround) {
  81189. this._ground.dispose();
  81190. this._ground = null;
  81191. }
  81192. if (this._groundMaterial && !newOptions.createGround) {
  81193. this._groundMaterial.dispose();
  81194. this._groundMaterial = null;
  81195. }
  81196. if (this._groundTexture) {
  81197. if (this._options.groundTexture != newOptions.groundTexture) {
  81198. this._groundTexture.dispose();
  81199. this._groundTexture = null;
  81200. }
  81201. }
  81202. if (this._skybox && !newOptions.createSkybox) {
  81203. this._skybox.dispose();
  81204. this._skybox = null;
  81205. }
  81206. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81207. this._skyboxMaterial.dispose();
  81208. this._skyboxMaterial = null;
  81209. }
  81210. if (this._skyboxTexture) {
  81211. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81212. this._skyboxTexture.dispose();
  81213. this._skyboxTexture = null;
  81214. }
  81215. }
  81216. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81217. this._groundMirror.dispose();
  81218. this._groundMirror = null;
  81219. }
  81220. if (this._scene.environmentTexture) {
  81221. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81222. this._scene.environmentTexture.dispose();
  81223. }
  81224. }
  81225. this._options = newOptions;
  81226. this._setupBackground();
  81227. this._setupImageProcessing();
  81228. };
  81229. /**
  81230. * Sets the primary color of all the available elements.
  81231. * @param color
  81232. */
  81233. EnvironmentHelper.prototype.setMainColor = function (color) {
  81234. if (this.groundMaterial) {
  81235. this.groundMaterial.primaryColor = color;
  81236. }
  81237. if (this.skyboxMaterial) {
  81238. this.skyboxMaterial.primaryColor = color;
  81239. }
  81240. if (this.groundMirror) {
  81241. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81242. }
  81243. };
  81244. /**
  81245. * Setup the image processing according to the specified options.
  81246. */
  81247. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81248. if (this._options.setupImageProcessing) {
  81249. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81250. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81251. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81252. this._setupEnvironmentTexture();
  81253. }
  81254. };
  81255. /**
  81256. * Setup the environment texture according to the specified options.
  81257. */
  81258. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81259. if (this._scene.environmentTexture) {
  81260. return;
  81261. }
  81262. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81263. this._scene.environmentTexture = this._options.environmentTexture;
  81264. return;
  81265. }
  81266. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81267. this._scene.environmentTexture = environmentTexture;
  81268. };
  81269. /**
  81270. * Setup the background according to the specified options.
  81271. */
  81272. EnvironmentHelper.prototype._setupBackground = function () {
  81273. if (!this._rootMesh) {
  81274. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81275. }
  81276. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81277. var sceneSize = this._getSceneSize();
  81278. if (this._options.createGround) {
  81279. this._setupGround(sceneSize);
  81280. this._setupGroundMaterial();
  81281. this._setupGroundDiffuseTexture();
  81282. if (this._options.enableGroundMirror) {
  81283. this._setupGroundMirrorTexture(sceneSize);
  81284. }
  81285. this._setupMirrorInGroundMaterial();
  81286. }
  81287. if (this._options.createSkybox) {
  81288. this._setupSkybox(sceneSize);
  81289. this._setupSkyboxMaterial();
  81290. this._setupSkyboxReflectionTexture();
  81291. }
  81292. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81293. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81294. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81295. };
  81296. /**
  81297. * Get the scene sizes according to the setup.
  81298. */
  81299. EnvironmentHelper.prototype._getSceneSize = function () {
  81300. var groundSize = this._options.groundSize;
  81301. var skyboxSize = this._options.skyboxSize;
  81302. var rootPosition = this._options.rootPosition;
  81303. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81304. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81305. }
  81306. var sceneExtends = this._scene.getWorldExtends();
  81307. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81308. if (this._options.sizeAuto) {
  81309. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81310. this._scene.activeCamera.upperRadiusLimit) {
  81311. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81312. skyboxSize = groundSize;
  81313. }
  81314. var sceneDiagonalLenght = sceneDiagonal.length();
  81315. if (sceneDiagonalLenght > groundSize) {
  81316. groundSize = sceneDiagonalLenght * 2;
  81317. skyboxSize = groundSize;
  81318. }
  81319. // 10 % bigger.
  81320. groundSize *= 1.1;
  81321. skyboxSize *= 1.5;
  81322. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81323. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81324. }
  81325. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81326. };
  81327. /**
  81328. * Setup the ground according to the specified options.
  81329. */
  81330. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81331. var _this = this;
  81332. if (!this._ground) {
  81333. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81334. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81335. this._ground.parent = this._rootMesh;
  81336. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81337. }
  81338. this._ground.receiveShadows = this._options.enableGroundShadow;
  81339. };
  81340. /**
  81341. * Setup the ground material according to the specified options.
  81342. */
  81343. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81344. if (!this._groundMaterial) {
  81345. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81346. }
  81347. this._groundMaterial.alpha = this._options.groundOpacity;
  81348. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81349. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81350. this._groundMaterial.primaryLevel = 1;
  81351. this._groundMaterial.primaryColor = this._options.groundColor;
  81352. this._groundMaterial.secondaryLevel = 0;
  81353. this._groundMaterial.tertiaryLevel = 0;
  81354. this._groundMaterial.useRGBColor = false;
  81355. this._groundMaterial.enableNoise = true;
  81356. if (this._ground) {
  81357. this._ground.material = this._groundMaterial;
  81358. }
  81359. };
  81360. /**
  81361. * Setup the ground diffuse texture according to the specified options.
  81362. */
  81363. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81364. if (!this._groundMaterial) {
  81365. return;
  81366. }
  81367. if (this._groundTexture) {
  81368. return;
  81369. }
  81370. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81371. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81372. return;
  81373. }
  81374. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81375. diffuseTexture.gammaSpace = false;
  81376. diffuseTexture.hasAlpha = true;
  81377. this._groundMaterial.diffuseTexture = diffuseTexture;
  81378. };
  81379. /**
  81380. * Setup the ground mirror texture according to the specified options.
  81381. */
  81382. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81383. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81384. if (!this._groundMirror) {
  81385. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81386. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81387. this._groundMirror.anisotropicFilteringLevel = 1;
  81388. this._groundMirror.wrapU = wrapping;
  81389. this._groundMirror.wrapV = wrapping;
  81390. this._groundMirror.gammaSpace = false;
  81391. if (this._groundMirror.renderList) {
  81392. for (var i = 0; i < this._scene.meshes.length; i++) {
  81393. var mesh = this._scene.meshes[i];
  81394. if (mesh !== this._ground &&
  81395. mesh !== this._skybox &&
  81396. mesh !== this._rootMesh) {
  81397. this._groundMirror.renderList.push(mesh);
  81398. }
  81399. }
  81400. }
  81401. }
  81402. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81403. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81404. };
  81405. /**
  81406. * Setup the ground to receive the mirror texture.
  81407. */
  81408. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81409. if (this._groundMaterial) {
  81410. this._groundMaterial.reflectionTexture = this._groundMirror;
  81411. this._groundMaterial.reflectionFresnel = true;
  81412. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81413. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81414. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81415. }
  81416. };
  81417. /**
  81418. * Setup the skybox according to the specified options.
  81419. */
  81420. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81421. var _this = this;
  81422. if (!this._skybox) {
  81423. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81424. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81425. }
  81426. this._skybox.parent = this._rootMesh;
  81427. };
  81428. /**
  81429. * Setup the skybox material according to the specified options.
  81430. */
  81431. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81432. if (!this._skybox) {
  81433. return;
  81434. }
  81435. if (!this._skyboxMaterial) {
  81436. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81437. }
  81438. this._skyboxMaterial.useRGBColor = false;
  81439. this._skyboxMaterial.primaryLevel = 1;
  81440. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81441. this._skyboxMaterial.secondaryLevel = 0;
  81442. this._skyboxMaterial.tertiaryLevel = 0;
  81443. this._skyboxMaterial.enableNoise = true;
  81444. this._skybox.material = this._skyboxMaterial;
  81445. };
  81446. /**
  81447. * Setup the skybox reflection texture according to the specified options.
  81448. */
  81449. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81450. if (!this._skyboxMaterial) {
  81451. return;
  81452. }
  81453. if (this._skyboxTexture) {
  81454. return;
  81455. }
  81456. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81457. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81458. return;
  81459. }
  81460. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81461. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81462. this._skyboxTexture.gammaSpace = false;
  81463. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81464. };
  81465. /**
  81466. * Dispose all the elements created by the Helper.
  81467. */
  81468. EnvironmentHelper.prototype.dispose = function () {
  81469. if (this._groundMaterial) {
  81470. this._groundMaterial.dispose(true, true);
  81471. }
  81472. if (this._skyboxMaterial) {
  81473. this._skyboxMaterial.dispose(true, true);
  81474. }
  81475. this._rootMesh.dispose(false);
  81476. };
  81477. /**
  81478. * Default ground texture URL.
  81479. */
  81480. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81481. /**
  81482. * Default skybox texture URL.
  81483. */
  81484. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81485. /**
  81486. * Default environment texture URL.
  81487. */
  81488. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81489. return EnvironmentHelper;
  81490. }());
  81491. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81492. })(BABYLON || (BABYLON = {}));
  81493. //# sourceMappingURL=babylon.environmentHelper.js.map
  81494. 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}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}"};
  81495. 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};"};
  81496. (function universalModuleDefinition(root, factory) {
  81497. var f = factory();
  81498. if (root && root["BABYLON"]) {
  81499. return;
  81500. }
  81501. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  81502. globalObject["BABYLON"] = f;
  81503. if(typeof exports === 'object' && typeof module === 'object')
  81504. module.exports = f;
  81505. else if(typeof define === 'function' && define.amd)
  81506. define(["BABYLON"], factory);
  81507. else if(typeof exports === 'object')
  81508. exports["BABYLON"] = f;
  81509. else {
  81510. root["BABYLON"] = f;
  81511. }
  81512. })(this, function() {
  81513. return BABYLON;
  81514. });